List of usage examples for com.itextpdf.text Image getInstance
public static Image getInstance(final Image image)
From source file:com.planning.project.controller.CreatePDF.java
private static void addTitlePageBud(Document document) throws DocumentException, IOException { Font font = new Font(BaseFont.createFont("D:/THSarabunNew.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED)); font.setSize(24);// www . j a v a 2 s .co m String imagepath = "src/main/webapp/resources/images/logo.jpg"; Image img = Image.getInstance(imagepath); img.scaleToFit(70f, 70f); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy"); Paragraph created = new Paragraph(); created.setFont(TIME_ROMAN_SMALL); created.add("Report created on " + simpleDateFormat.format(new Date())); created.setAlignment(Element.ALIGN_RIGHT); Paragraph logo = new Paragraph(); logo.setFont(TIME_ROMAN_SMALL); logo.add(img); logo.setAlignment(Element.ALIGN_LEFT); document.add(created); document.add(logo); // Paragraph created = new Paragraph(); // created.setFont(TIME_ROMAN_SMALL); // created.add("Report created on " + simpleDateFormat.format(new // Date())); // created.setAlignment(Element.ALIGN_RIGHT); Paragraph paragraph = new Paragraph(); paragraph.setFont(font); paragraph.add( "?"); paragraph.setAlignment(Element.ALIGN_CENTER); document.add(paragraph); creteEmptyLine(created, 1); }
From source file:com.pos1.ThirdPage.java
public static PdfPCell createImageCell(String path) throws DocumentException, IOException { Image img = Image.getInstance(path); PdfPCell cell = new PdfPCell(img, true); return cell;/*from w w w . j a v a 2s. c o m*/ }
From source file:com.primeleaf.krystal.util.PDFConverter.java
License:Open Source License
public File getConvertedFile(DocumentRevision documentRevision, Document document, String password) throws Exception { File tempFile = documentRevision.getDocumentFile(); if ("TIF".equalsIgnoreCase(document.getExtension()) || "TIFF".equalsIgnoreCase(document.getExtension())) { try {// www . j av a 2 s. c o m tempFile = File.createTempFile("temp", ".PDF"); com.itextpdf.text.Document pdf = new com.itextpdf.text.Document(); PdfWriter.getInstance(pdf, new FileOutputStream(tempFile)); pdf.open(); pdf.setMargins(0, 0, 0, 0); FileInputStream fis = new FileInputStream(documentRevision.getDocumentFile()); RandomAccessFileOrArray file = new RandomAccessFileOrArray(fis); int pages = TiffImage.getNumberOfPages(file); for (int page = 1; page <= pages; page++) { Image img = TiffImage.getTiffImage(file, page); img.setAbsolutePosition(0f, 0f); img.scaleToFit(PageSize.A4.getWidth(), PageSize.A4.getHeight()); pdf.setMargins(0, 0, 0, 0); pdf.add(img); pdf.newPage(); } fis.close(); pdf.close(); document.setExtension("PDF"); } catch (Exception e) { tempFile = documentRevision.getDocumentFile(); throw new Exception("Unable to convert TIFF Document to PDF"); } } else if ("JPG".equalsIgnoreCase(document.getExtension()) || "JPEG".equalsIgnoreCase(document.getExtension()) || "PNG".equalsIgnoreCase(document.getExtension()) || "BMP".equalsIgnoreCase(document.getExtension()) || "GIF".equalsIgnoreCase(document.getExtension())) { try { tempFile = File.createTempFile("temp", ".PDF"); Image img = Image.getInstance(documentRevision.getDocumentFile().getAbsolutePath()); com.itextpdf.text.Document pdf = new com.itextpdf.text.Document( new Rectangle(img.getWidth(), img.getHeight()), 0, 0, 0, 0); img.setAbsolutePosition(0f, 0f); PdfWriter.getInstance(pdf, new FileOutputStream(tempFile)); pdf.open(); pdf.add(img); pdf.close(); document.setExtension("PDF"); } catch (Exception e) { tempFile = documentRevision.getDocumentFile(); throw new Exception("Unable to convert Image Document to PDF"); } } else if ("PDF".equalsIgnoreCase(document.getExtension())) { tempFile = documentRevision.getDocumentFile(); } else { String tempFilePath = ""; String KRYSTAL_HOME = System.getProperty("krystal.home"); if (KRYSTAL_HOME == null) { KRYSTAL_HOME = System.getProperty("user.dir"); System.setProperty("krystal.home", KRYSTAL_HOME); } tempFilePath = KRYSTAL_HOME + File.separator + "/webapps/DMC/images/unsupport.pdf"; tempFile = new File(tempFilePath); } return tempFile; }
From source file:com.prjhuellvotweb.controlador.PDF.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Preguntar por la sesion del usuario admin HttpSession sessionOk = request.getSession(true); if (sessionOk.getAttribute("admin") != null) { //cambiar a tipo application/pdf response.setContentType("application/pdf;charset=UTF-8"); //flujo de salida OutputStream out = response.getOutputStream(); String texto = request.getParameter("report"); //texto = "Reporte de los proyectos Sena CTGI (Centro tecnologico de gestion industrial) donde se dan a conocer" // + " los nombres de los proyectos y cantidad de votos obtenidos para cada proyecto."; try {//from w w w . j av a 2s.co m Connection con = Conexion.conectar("mysql"); DAOVoto dao = new DAOVoto(); List<List> lista = dao.estadisticaNumeroVotos(); Voto t = dao.contarVotos(); int to = t.getIdUsuario(); if (!lista.isEmpty() && lista.size() > 0) { try { //programar pdf Document documento = new Document(); //asosciar documento con la salida PdfWriter.getInstance(documento, out);// salida del cocumento en pdf //abrir documento documento.open(); Paragraph par2 = new Paragraph(); Paragraph par4 = new Paragraph(); //agregar una imagen logo sena al pdf Image imagenes = Image .getInstance(getServletContext().getRealPath("") + "/Multimedia/reportes.png"); //Centrar la imagen imagenes.setAlignment(Element.ALIGN_CENTER); //tamao de la imagen imagenes.scaleToFit(530, 520); //agg imagen al documento F:\\Documentos\\yo\\huellvot 2 17-06-2016\\PrjHuellVotWeb\\web\\iCO.png //documento.add(imghuellvot); documento.add(imagenes); //Agg salto de linea par2.add(new Phrase(Chunk.NEWLINE)); par2.add(new Phrase(Chunk.NEWLINE)); //fuente del pdf, tipo de fuente famimilia tamao de letra //Importar ttf que contiene el tipo de letra FontFactory.register( "C:\\Users\\pc\\Desktop\\PrjHuellVotWeb\\web\\fonts\\roboto\\Roboto-Bold.ttf", "Roboto"); //Font fondescripcion = FontFactory.getFont("Roboto"); Font fondescripcion = new Font(Font.getFamily("Roboto"), 16, Font.NORMAL, BaseColor.BLACK); //texto de la descripcion par2.add(new Phrase(texto, fondescripcion)); //justificar descripcion par2.setAlignment(Element.ALIGN_JUSTIFIED); //Agg salto de linea par2.add(new Phrase(Chunk.NEWLINE)); par2.add(new Phrase(Chunk.NEWLINE)); //agregar descripcion al documento documento.add(par2);//agregar todas las propiedades de la descripcin //crear una tabla PdfPTable tabla = new PdfPTable(5);//( Numero de columnas de la tabla) //columnas de la tabla, cabezera y agg un estilo PdfPCell celda = new PdfPCell( new Paragraph("Nmero", FontFactory.getFont("Roboto", 14, Font.BOLD))); PdfPCell celda1 = new PdfPCell( new Paragraph("Nombre", FontFactory.getFont("Roboto", 14, Font.BOLD))); celda1.setColspan(3); PdfPCell celda2 = new PdfPCell( new Paragraph("Votos", FontFactory.getFont("Roboto", 14, Font.BOLD))); //Color de fondo celda.setBackgroundColor(new BaseColor(252, 115, 35)); celda1.setBackgroundColor(new BaseColor(252, 115, 35)); celda2.setBackgroundColor(new BaseColor(252, 115, 35)); //Centrar celda.setHorizontalAlignment(Element.ALIGN_CENTER); celda1.setHorizontalAlignment(Element.ALIGN_CENTER); celda2.setHorizontalAlignment(Element.ALIGN_CENTER); //padding celda.setPadding(8.0f); celda1.setPadding(8.0f); celda2.setPadding(8.0f); //agg columna ala tabla tabla.addCell(celda); tabla.addCell(celda1); tabla.addCell(celda2); for (int i = 0; i < lista.size(); i++) { List l = lista.get(i); //Convertir el entero a string String num = String.valueOf(l.get(0)); String nom = String.valueOf(l.get(1)); String tot = String.valueOf(l.get(2)); //Agregar valores a las celdas PdfPCell c = new PdfPCell( new Paragraph(num, FontFactory.getFont("Roboto", 12, Font.BOLD))); PdfPCell c1 = new PdfPCell( new Paragraph(nom, FontFactory.getFont("Roboto", 12, Font.BOLD))); c1.setColspan(3); PdfPCell c2 = new PdfPCell( new Paragraph(tot, FontFactory.getFont("Roboto", 12, Font.BOLD))); //Padding para las celdas c.setPadding(4.0f); c1.setPadding(4.0f); c2.setPadding(4.0f); //Centrar contenido de celda c.setHorizontalAlignment(Element.ALIGN_CENTER); c2.setHorizontalAlignment(Element.ALIGN_CENTER); //mostrar los resultados de cada columna los agrega a la tabla tabla.addCell(c); tabla.addCell(c1); tabla.addCell(c2); } PdfPCell c1 = new PdfPCell(new Paragraph("Total Votos: ", fondescripcion)); c1.setColspan(4); PdfPCell c2 = new PdfPCell(new Paragraph("" + to, fondescripcion)); c1.setHorizontalAlignment(Element.ALIGN_CENTER); c2.setHorizontalAlignment(Element.ALIGN_CENTER); c1.setPadding(4.0f); c2.setPadding(4.0f); tabla.addCell(c1); tabla.addCell(c2); //Agrega la tabla a el documento documento.add(tabla); //agregar fecha Font fonfecha = new Font(Font.getFamily("Roboto"), 12, Font.NORMAL, BaseColor.LIGHT_GRAY); par4.add(new Phrase("Expedido por HuellVot", fonfecha)); DateFormat formato = DateFormat.getDateInstance(DateFormat.FULL); par4.add(new Paragraph(formato.format(new Date()))); documento.add(par4); //cerrar el documento documento.close(); } catch (DocumentException | IOException e) { e.getMessage(); System.out.println("Error al generar el reporte PDF" + e); } } else { try { Document documento = new Document(); PdfWriter.getInstance(documento, out);// salida del cocumento en pdf //abrir documento documento.open(); System.out.println("no hat datos"); //agregar una imagen logo sena al pdf Image imagenes = Image.getInstance( "C:\\Users\\pc\\Desktop\\PrjHuellVotWeb\\web\\Multimedia\\reportes.png"); //Centrar la imagen imagenes.setAlignment(Element.ALIGN_CENTER); //tamao de la imagen imagenes.scaleToFit(530, 520); //agg imagen al documento F:\\Documentos\\yo\\huellvot 2 17-06-2016\\PrjHuellVotWeb\\web\\iCO.png //documento.add(imghuellvot); documento.add(imagenes); Paragraph par1 = new Paragraph(); Paragraph par2 = new Paragraph(); //Agg salto de linea par1.add(new Phrase(Chunk.NEWLINE)); par1.add(new Phrase(Chunk.NEWLINE)); //fuente del pdf, tipo de fuente famimilia tamao de letra //Importar ttf que contiene el tipo de letra FontFactory.register( "C:\\Users\\pc\\Desktop\\PrjHuellVotWeb\\web\\fonts\\roboto\\Roboto-Bold.ttf", "Roboto"); //Font fondescripcion = FontFactory.getFont("Roboto"); Font fondescripcion = new Font(Font.getFamily("Roboto"), 16, Font.NORMAL, BaseColor.BLACK); //texto de la descripcion par1.add(new Phrase("lo sentimos pero no hay datos para mostrar.!", fondescripcion)); //justificar descripcion par1.setAlignment(Element.ALIGN_CENTER); //Agg salto de linea par1.add(new Phrase(Chunk.NEWLINE)); par1.add(new Phrase(Chunk.NEWLINE)); //agregar descripcion al documento documento.add(par1);//agregar todas las propiedades de la descripcin //agregar fecha Font fonfecha = new Font(Font.getFamily("Roboto"), 12, Font.NORMAL, BaseColor.LIGHT_GRAY); par2.add(new Phrase("Expedido por HuellVot", fonfecha)); DateFormat formato = DateFormat.getDateInstance(DateFormat.FULL); par2.add(new Paragraph(formato.format(new Date()))); documento.add(par2); //cerrar el documento documento.close(); } catch (DocumentException ex) { ex.getMessage(); System.out.println("Error al generar el reporte PDF sin datos registrados" + ex); } } } finally { out.close(); } } else { sessionOk.invalidate(); response.sendRedirect("index.jsp"); } }
From source file:com.quix.aia.cn.imo.mapper.ApplicationFormPDFMaintenance.java
License:Open Source License
private static Document ESingnature(Document document, PdfWriter writer, AddressBook addressbook) { // TODO Auto-generated method stub log.log(Level.INFO, "ApplicationFormPDFMaintenance --> ESingnature "); try {// ww w . ja va2 s . co m document.newPage(); PdfPTable table = new PdfPTable(2); table.setSpacingBefore(10); table.setWidthPercentage(100f); PdfPCell c1 = new PdfPCell(new Phrase("E-singnature ")); c1.setHorizontalAlignment(Element.ALIGN_LEFT); c1.setColspan(4); c1.setBorder(Rectangle.LEFT | Rectangle.RIGHT | Rectangle.TOP); c1.setFixedHeight(30f); c1.setBackgroundColor(BaseColor.LIGHT_GRAY); c1.setBorder(Rectangle.BOX); c1.setFixedHeight(25f); table.addCell(c1); table.setHeaderRows(1); for (int i = 0; i < 2; i++) { c1 = new PdfPCell(new Phrase(" ", font)); c1.setBorder(Rectangle.NO_BORDER); c1.setLeading(4f, 0f); c1.setFixedHeight(15f); table.addCell(c1); } Iterator itr = null; CandidateESignature esignature = new CandidateESignature(); if (addressbook.getCandidateESignatures().size() > 0) { itr = addressbook.getCandidateESignatures().iterator(); esignature = (CandidateESignature) itr.next(); } c1 = new PdfPCell(new Phrase("Branch : " + esignature.getBranch(), font)); c1.setBorder(Rectangle.NO_BORDER); c1.setLeading(4f, 0f); c1.setFixedHeight(15f); c1.setBorder(Rectangle.BOTTOM); table.addCell(c1); c1 = new PdfPCell(new Phrase("Servicing Department : " + esignature.getServiceDepartment(), font)); c1.setBorder(Rectangle.NO_BORDER); c1.setLeading(4f, 0f); c1.setFixedHeight(15f); c1.setBorder(Rectangle.BOTTOM); table.addCell(c1); for (int i = 0; i < 2; i++) { c1 = new PdfPCell(new Phrase(" ", font)); c1.setBorder(Rectangle.NO_BORDER); c1.setLeading(4f, 0f); c1.setFixedHeight(15f); table.addCell(c1); } c1 = new PdfPCell(new Phrase("City : " + esignature.getCity(), font)); c1.setBorder(Rectangle.NO_BORDER); c1.setLeading(4f, 0f); c1.setFixedHeight(15f); c1.setBorder(Rectangle.BOTTOM); table.addCell(c1); c1 = new PdfPCell(new Phrase("Agent Code : " + esignature.getAgentId(), font)); c1.setBorder(Rectangle.NO_BORDER); c1.setLeading(4f, 0f); c1.setFixedHeight(15f); c1.setBorder(Rectangle.BOTTOM); table.addCell(c1); for (int i = 0; i < 4; i++) { c1 = new PdfPCell(new Phrase(" ", font)); c1.setBorder(Rectangle.NO_BORDER); c1.setLeading(4f, 0f); c1.setFixedHeight(15f); table.addCell(c1); } document.add(table); table = new PdfPTable(2); table.setSpacingBefore(10); table.setWidthPercentage(100f); table.setWidths(new int[] { 80, 20 }); c1 = new PdfPCell(new Phrase("Presently attached with another insurance Company ? ", font)); c1.setBorder(Rectangle.NO_BORDER); c1.setLeading(4f, 0f); c1.setFixedHeight(15f); table.addCell(c1); c1 = new PdfPCell(new Phrase("Yes \t\t\t\t\t\t\t\t No", font)); c1.setBorder(Rectangle.NO_BORDER); c1.setLeading(4f, 0f); c1.setFixedHeight(15f); table.addCell(c1); for (int i = 0; i < 2; i++) { c1 = new PdfPCell(new Phrase(" ", font)); c1.setBorder(Rectangle.NO_BORDER); c1.setLeading(4f, 0f); c1.setFixedHeight(15f); table.addCell(c1); } c1 = new PdfPCell( new Phrase("Presently in contact with any other AIA'S servicing Department ? ", font)); c1.setBorder(Rectangle.NO_BORDER); c1.setLeading(4f, 0f); c1.setFixedHeight(15f); table.addCell(c1); c1 = new PdfPCell(new Phrase("Yes \t\t\t\t\t\t\t\t No", font)); c1.setBorder(Rectangle.NO_BORDER); c1.setLeading(4f, 0f); c1.setFixedHeight(15f); table.addCell(c1); for (int i = 0; i < 2; i++) { c1 = new PdfPCell(new Phrase(" ", font)); c1.setBorder(Rectangle.NO_BORDER); c1.setLeading(4f, 0f); c1.setFixedHeight(15f); table.addCell(c1); } c1 = new PdfPCell( new Phrase("Taken LOMBRA occupational test or PSP test in the past ? If Yes, ", font)); c1.setBorder(Rectangle.NO_BORDER); c1.setLeading(4f, 0f); c1.setFixedHeight(15f); table.addCell(c1); c1 = new PdfPCell(new Phrase("Yes \t\t\t\t\t\t\t\t No", font)); c1.setBorder(Rectangle.NO_BORDER); c1.setLeading(4f, 0f); c1.setFixedHeight(15f); table.addCell(c1); for (int i = 0; i < 2; i++) { c1 = new PdfPCell(new Phrase(" ", font)); c1.setBorder(Rectangle.NO_BORDER); c1.setLeading(4f, 0f); c1.setFixedHeight(15f); table.addCell(c1); } c1 = new PdfPCell(new Phrase("Please provide the result. ", font)); c1.setBorder(Rectangle.NO_BORDER); c1.setLeading(4f, 0f); c1.setFixedHeight(15f); table.addCell(c1); for (int i = 0; i < 5; i++) { c1 = new PdfPCell(new Phrase(" ", font)); c1.setBorder(Rectangle.NO_BORDER); c1.setLeading(4f, 0f); c1.setFixedHeight(15f); table.addCell(c1); } document.add(table); Paragraph para1 = new Paragraph(); para1.add(new Chunk("Applicant's Declaration ", font)); para1.setAlignment(Element.ALIGN_LEFT); para1.setSpacingAfter(5f); document.add(para1); table = new PdfPTable(2); table.setSpacingBefore(10); table.setWidthPercentage(100f); for (int i = 0; i < 4; i++) { c1 = new PdfPCell(new Phrase(" ", font)); c1.setBorder(Rectangle.NO_BORDER); c1.setLeading(4f, 0f); c1.setFixedHeight(15f); table.addCell(c1); c1 = new PdfPCell(new Phrase(" ", font)); c1.setBorder(Rectangle.NO_BORDER); c1.setLeading(4f, 0f); c1.setFixedHeight(15f); table.addCell(c1); } c1 = new PdfPCell(new Phrase("Application Date", font)); c1.setBorder(Rectangle.NO_BORDER); c1.setLeading(4f, 0f); c1.setFixedHeight(15f); table.addCell(c1); c1 = new PdfPCell(new Phrase("Applicant/Candidate Name :", font)); c1.setBorder(Rectangle.NO_BORDER); c1.setLeading(4f, 0f); c1.setFixedHeight(15f); table.addCell(c1); if (esignature.getApplicationDate() != null) { c1 = new PdfPCell(new Phrase(format.format(esignature.getApplicationDate()), font)); c1.setBorder(Rectangle.NO_BORDER); c1.setLeading(4f, 0f); c1.setFixedHeight(15f); table.addCell(c1); } else { c1 = new PdfPCell(new Phrase("", font)); c1.setBorder(Rectangle.NO_BORDER); c1.setLeading(4f, 0f); c1.setFixedHeight(15f); table.addCell(c1); } c1 = new PdfPCell(new Phrase(esignature.getCandidateName(), font)); c1.setBorder(Rectangle.NO_BORDER); c1.setLeading(4f, 0f); c1.setFixedHeight(15f); table.addCell(c1); for (int i = 0; i < 4; i++) { c1 = new PdfPCell(new Phrase(" ", font)); c1.setBorder(Rectangle.NO_BORDER); c1.setLeading(4f, 0f); c1.setFixedHeight(15f); table.addCell(c1); c1 = new PdfPCell(new Phrase(" ", font)); c1.setBorder(Rectangle.NO_BORDER); c1.setLeading(4f, 0f); c1.setFixedHeight(15f); table.addCell(c1); } document.add(table); para1 = new Paragraph(); para1.add(new Chunk("E-Signature : ", font)); para1.setAlignment(Element.ALIGN_LEFT); para1.setSpacingAfter(5f); document.add(para1); c1 = new PdfPCell(new Phrase(" ", font)); c1.setBorder(Rectangle.NO_BORDER); c1.setLeading(4f, 0f); c1.setFixedHeight(15f); table.addCell(c1); if (esignature.geteSignaturePhoto() != null) { Image image = Image.getInstance(esignature.geteSignaturePhoto()); para1 = new Paragraph(); para1.add(image); para1.setAlignment(Element.ALIGN_LEFT); para1.setSpacingAfter(5f); document.add(para1); } else { para1 = new Paragraph(); para1.add(""); para1.setAlignment(Element.ALIGN_LEFT); para1.setSpacingAfter(5f); document.add(para1); } } catch (Exception e) { // TODO Auto-generated catch block log.log(Level.INFO, "ApplicationFormPDFMaintenance --> ESingnature " + e.getMessage()); e.printStackTrace(); e.printStackTrace(); LogsMaintenance logsMain = new LogsMaintenance(); StringWriter errors = new StringWriter(); e.printStackTrace(new PrintWriter(errors)); logsMain.insertLogs("ApplicationFormPDFMaintenance", Level.SEVERE + "", errors.toString()); } return document; }
From source file:com.raghav.plot.ImageIntoPDF.java
public static void main(String[] args) throws Exception { Document document = new Document(PageSize.A4); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("/home/raghav/zzzzz.pdf")); document.open();//from w ww . java 2 s . c om document.newPage(); //for 4 photo // for (int i=0;i<2;i++) { // Image image1 = Image.getInstance("/home/raghav/Desktop/Firmway-Reco.png"); // image1.setAbsolutePosition(40,80+(350*i)); // image1.scaleAbsolute(200, 260); // document.add(image1); // } // for (int i=0;i<2;i++) { // Image image1 = Image.getInstance("/home/raghav/Desktop/Firmway-Reco.png"); // image1.setAbsolutePosition(300, 80+(350*i)); // image1.scaleAbsolute(260, 200); // document.add(image1); // } //for 6 float margin = 10; float docHeight = ((document.getPageSize().getHeight()) / 3) - (2 * margin); float docwidth = ((document.getPageSize().getWidth()) / 2) - (2 * margin); for (int i = 0; i < 3; i++) { Image image1 = Image.getInstance("/home/raghav/myps/i1.jpeg"); image1.setAbsolutePosition(margin, margin * (i + 1) + (docHeight * i)); image1.scaleToFit(docwidth, docHeight); //image1.scaleAbsolute(190, 130); document.add(image1); } for (int i = 0; i < 3; i++) { Image image1 = Image.getInstance("/home/raghav/myps/i1.jpeg"); image1.setAbsolutePosition(docwidth + (2 * margin), margin * (i + 1) + (docHeight * i)); image1.scaleToFit(docwidth, docHeight); document.add(image1); } document.close(); }
From source file:com.rapidminer.gui.actions.ExportPdfAction.java
License:Open Source License
/** * Creates a pdf showing the given {@link Component} via {@link PdfTemplate} usage. * @param component/*from w w w . j a va2s.c om*/ * @param document * @param cb * @throws DocumentException */ private void createPdfViaTemplate(Component component, Document document, PdfContentByte cb) throws DocumentException { PdfTemplate tp = cb.createTemplate(500, PageSize.A4.getHeight() / 2); Graphics2D g2 = tp.createGraphics(500, PageSize.A4.getHeight() / 2); // special handling for charts as we only want to export the chart but not the control panel // chart cannot be scaled to size of component because otherwise we would break the chart aspect-ratio if (component.getClass().isAssignableFrom(JPanel.class)) { JPanel panel = (JPanel) component; if (panel.getLayout().getClass().isAssignableFrom(CardLayout.class)) { for (final Component comp : panel.getComponents()) { // iterate over all card components and see if there is a chart which would require special handling // if not we don't do anything in this loop and do the standard behavior at the bottom of the method if (comp.isVisible() && ChartConfigurationPanel.class.isAssignableFrom(comp.getClass())) { final ChartConfigurationPanel chartConfigPanel = (ChartConfigurationPanel) comp; // create new LinkAndBrushChartPanel with double buffering set to false to get vector graphic export // The real chart has to use double buffering for a) performance and b) zoom rectangle drawing LinkAndBrushChartPanel newLaBPanel = new LinkAndBrushChartPanel( chartConfigPanel.getPlotEngine().getChartPanel().getChart(), chartConfigPanel.getPlotEngine().getChartPanel().getWidth(), chartConfigPanel.getPlotEngine().getChartPanel().getHeight(), chartConfigPanel.getPlotEngine().getChartPanel().getMinimumDrawWidth(), chartConfigPanel.getPlotEngine().getChartPanel().getMinimumDrawHeight(), false, false); newLaBPanel.setSize(chartConfigPanel.getPlotEngine().getChartPanel().getSize()); newLaBPanel .setOverlayList(chartConfigPanel.getPlotEngine().getChartPanel().getOverlayList()); AffineTransform at = new AffineTransform(); double factor = 500d / chartConfigPanel.getPlotEngine().getChartPanel().getWidth(); at.scale(factor, factor); g2.transform(at); newLaBPanel.print(g2); g2.dispose(); document.add(new Paragraph(componentName)); document.add(Image.getInstance(tp)); return; } else if (comp.isVisible() && PlotterPanel.class.isAssignableFrom(comp.getClass())) { // special case for PlotterPanel as the Panel itself is wider than the plotter // not having a special case here results in the exported image being too wide (empty space to the left) final PlotterPanel plotterPanel = (PlotterPanel) comp; AffineTransform at = new AffineTransform(); double factor = 500d / plotterPanel.getPlotterComponent().getWidth(); at.scale(factor, factor); g2.transform(at); plotterPanel.print(g2); g2.dispose(); document.add(new Paragraph(componentName)); document.add(Image.getInstance(tp)); return; } } } } AffineTransform at = new AffineTransform(); double factor = 500d / component.getWidth(); at.scale(factor, factor); g2.transform(at); component.print(g2); g2.dispose(); document.add(new Paragraph(componentName)); document.add(Image.getInstance(tp)); }
From source file:com.rapidminer.gui.actions.ExportPdfAction.java
License:Open Source License
/** * Creates a pdf showing the given {@link PlotterTemplate} via {@link PdfTemplate} usage. * @param template/*from w ww.ja va2s. com*/ * @param document * @param cb * @throws DocumentException */ private void createPdfViaTemplate(PlotterTemplate template, Document document, PdfContentByte cb) throws DocumentException { PdfTemplate tp = cb.createTemplate(500, PageSize.A4.getHeight() / 2); Graphics2D g2 = tp.createGraphics(500, PageSize.A4.getHeight() / 2); AffineTransform at = new AffineTransform(); double factor = 500d / template.getPlotEngine().getChartPanel().getWidth(); at.scale(factor, factor); g2.transform(at); template.getPlotEngine().getChartPanel().print(g2); g2.dispose(); document.add(new Paragraph(componentName)); document.add(Image.getInstance(tp)); }
From source file:com.sapito.pdf.PDFView.PDFGeneratorActivosFijos.java
public void crearPDFInversion(HttpServletResponse hsr1, ArrayList<HashMap> resultados, double granTotalDepActual, double granTotalValorActual, double granTotalValorOr) throws Exception { Document dcmntaf = new Document(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter.getInstance(dcmntaf, baos); System.out.println(resultados.get(0).size()); dcmntaf.open();// w w w . j a va2s . co m dcmntaf.open(); dcmntaf.addTitle("Sapito PDFs"); dcmntaf.addSubject("Pdf de sapito"); //------------------------ TAIS ______________________________ Image tais = Image.getInstance(new URL("http://localhost:8080/SAPITO/resources/img/tais-banner.jpg")); dcmntaf.add(tais); //--------------------- BODY --------------------------------------------------------- Image body = Image.getInstance(new URL("http://localhost:8080/SAPITO/resources/img/body.png")); body.setAlignment(Image.UNDERLYING); body.setTransparency(new int[] { 0x00, 0x10 }); body.setAbsolutePosition(50, 250); dcmntaf.add(body); //------------------------------------------------------------------------------------------- Image footer = Image.getInstance(new URL("http://localhost:8080/SAPITO/resources/img/footer.jpg")); footer.setAbsolutePosition(50, 20); dcmntaf.add(footer); //---------------------- TITLE --------------------------- String titulo = "Reporte de Inversin"; //Cambiar el titulo del PDF aqui Font f = new Font(FontFamily.HELVETICA, 25.0f, Font.BOLD, BaseColor.BLACK); Chunk c = new Chunk(titulo + " \n ", f); c.setBackground(BaseColor.WHITE); Paragraph title = new Paragraph(c); title.setAlignment(Element.ALIGN_CENTER); String titulo2 = "Reporte de Activos Fijos por Tipo"; //Cambiar el titulo del PDF aqui Font f2 = new Font(FontFamily.HELVETICA, 12.0f, Font.NORMAL, BaseColor.BLACK); Chunk c2 = new Chunk(titulo2 + " \n ", f2); c2.setBackground(BaseColor.WHITE); Paragraph title2 = new Paragraph(c2); title2.setAlignment(Element.ALIGN_LEFT); title2.setIndentationLeft(50); //------------------------- CONTENIDO ------------------------------------------------------- dcmntaf.add(title); //Titulo del PDF dcmntaf.add(title2); PdfPTable table = new PdfPTable(4); // PdfPCell cell; // cell = new PdfPCell(new Phrase("Tipo de A", FontFactory.getFont("TIMES_ROMAN", 12, Font.BOLD, BaseColor.BLACK))); // table.addCell(cell); table.addCell("Tipo de Activo fijo"); table.addCell("Valor Original"); table.addCell("Depreciacin Actual "); table.addCell("Valor Actual"); // Iterator it = resultados.get(0).entrySet().iterator(); for (int i = 0; i < resultados.size(); i++) { table.addCell(resultados.get(i).get("tipo").toString()); table.addCell(resultados.get(i).get("valorOriginal").toString()); table.addCell(resultados.get(i).get("depreciacionActual").toString()); table.addCell(resultados.get(i).get("valoreActual").toString()); } // while (it.hasNext()) { // Map.Entry e = (Map.Entry) it.next(); // System.out.println(e.getKey() + " " + e.getValue()); // // table.addCell(e.getValue().toString()); // } dcmntaf.add(table); String titulo3 = "Reporte Total de Activos Fijos"; //Cambiar el titulo del PDF aqui Font f3 = new Font(FontFamily.HELVETICA, 12.0f, Font.NORMAL, BaseColor.BLACK); Chunk c3 = new Chunk(titulo3 + " \n ", f3); c3.setBackground(BaseColor.WHITE); Paragraph title3 = new Paragraph(c3); title3.setAlignment(Element.ALIGN_LEFT); title3.setIndentationLeft(50); dcmntaf.add(title3); PdfPTable table2 = new PdfPTable(3); // PdfPCell cell; // cell = new PdfPCell(new Phrase("Tipo de A", FontFactory.getFont("TIMES_ROMAN", 12, Font.BOLD, BaseColor.BLACK))); // table.addCell(cell); table2.addCell("Valor Original Total"); table2.addCell("Depreciacin Anual Total"); table2.addCell("Valor Total"); table2.addCell(granTotalValorOr + ""); table2.addCell(granTotalDepActual + ""); table2.addCell(granTotalValorActual + ""); dcmntaf.add(table2); PdfPTable table3 = new PdfPTable(1); table3.setWidthPercentage(100.0f); table3.setWidths(new float[] { 2.0f }); table3.setSpacingBefore(10); // define font for table header row Font font = FontFactory.getFont(FontFactory.COURIER_BOLD); font.setColor(BaseColor.WHITE); // define table header cell PdfPCell cell = new PdfPCell(); cell.setBackgroundColor(BaseColor.BLUE); cell.setPadding(5); // write table header cell.setPhrase(new Phrase("Resultado", font)); table3.addCell(cell); Depreciacion dep = new Depreciacion(); String bla = a + " "; table3.addCell(bla); //-------------------------- FIN CONTENIDO ----------------- dcmntaf.close(); dcmntaf.close(); byte[] bytes = baos.toByteArray(); hsr1.setContentType("application/pdf"); hsr1.setContentLength(bytes.length); hsr1.getOutputStream().write(bytes); }
From source file:com.sapito.pdf.PDFView.PDFGeneratorContabilidad.java
public void crearEstadoResultados(HttpServletResponse hsr1, String ingresos, String cVenta, String cGeneral, String cImpu, String cImpTot) throws Exception { Document document = new Document(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter.getInstance(document, baos); document.open();/*from ww w .ja v a2s.com*/ document.addTitle("Sapito PDFs"); document.addSubject("Pdf de sapito"); //------------------------ TAIS ______________________________ Image tais = Image.getInstance(new URL("http://localhost:8080/SAPITO/resources/img/tais-banner.jpg")); document.add(tais); //--------------------- BODY --------------------------------------------------------- Image body = Image.getInstance(new URL("http://localhost:8080/SAPITO/resources/img/body.png")); body.setAlignment(Image.UNDERLYING); body.setTransparency(new int[] { 0x00, 0x10 }); body.setAbsolutePosition(50, 250); document.add(body); //------------------------------------------------------------------------------------------- Image footer = Image.getInstance(new URL("http://localhost:8080/SAPITO/resources/img/footer.jpg")); footer.setAbsolutePosition(50, 20); document.add(footer); //---------------------- TITLE --------------------------- String titulo = "Estado de Resultados"; //Cambiar el titulo del PDF aqui Font f = new Font(FontFamily.HELVETICA, 25.0f, Font.BOLD, BaseColor.BLACK); Chunk c = new Chunk(titulo + " \n ", f); c.setBackground(BaseColor.WHITE); Paragraph title = new Paragraph(c); title.setAlignment(Element.ALIGN_CENTER); //------------------------- CONTENIDO ------------------------------------------------------- document.add(title); //Titulo del PDF PdfPTable table = new PdfPTable(2); table.addCell("Ingresos"); table.addCell(ingresos);//valor table.addCell("Costo de Venta"); table.addCell(cVenta);//valor table.addCell("Costos Generales"); table.addCell(cGeneral);//valor table.addCell("Impuestos de Ingresos"); table.addCell(cImpu);//valor table.addCell("Impuesto de Costos Totales"); table.addCell(cImpTot);//valor document.add(table); document.close(); byte[] bytes = baos.toByteArray(); hsr1.setContentType("application/pdf"); hsr1.setContentLength(bytes.length); hsr1.getOutputStream().write(bytes); }