public void generatePdf() { java.lang.Process wait_for_Pdf2Show; java.util.Calendar cal = java.util.Calendar.getInstance(); java.util.Date dateStampPdf = cal.getTime(); java.lang.String pdfDateStamp = dateStampPdf.toString(); try { java.io.File tempFile = java.io.File.createTempFile("REP" + this.getDateLable() + "_", ".pdf"); tempFile.deleteOnExit(); java.lang.Runtime rt = java.lang.Runtime.getRuntime(); java.lang.String debitTotal = null; java.lang.String creditTotal = null; com.lowagie.text.Document docPdf = new com.lowagie.text.Document(); try { try { com.lowagie.text.pdf.PdfWriter.getInstance( docPdf, new java.io.FileOutputStream(tempFile)); String compName = null; String date = null; try { java.sql.Statement st3 = connectDB.createStatement(); java.sql.Statement st4 = connectDB.createStatement(); java.sql.Statement st2x = connectDB.createStatement(); java.sql.ResultSet rset2x = st2x.executeQuery("SELECT rep_currency from pb_hospitalprofile"); while (rset2x.next()) { ks = rset2x.getObject(1).toString(); } java.sql.ResultSet rset2 = st3.executeQuery("SELECT hospital_name from pb_hospitalprofile"); java.sql.ResultSet rset4 = st4.executeQuery("SELECT date('now') as Date"); while (rset2.next()) { compName = rset2.getObject(1).toString(); } while (rset4.next()) { date = rset4.getObject(1).toString(); } com.lowagie.text.HeaderFooter headerFoter = new com.lowagie.text.HeaderFooter( new Phrase("" + compName), false); // FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 14, // Font.BOLDITALIC,java.awt.Color.blue))); // com.lowagie.text.HeaderFooter headerFoter = new com.lowagie.text.HeaderFooter(new // Phrase(""+compName+""),false);// // FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 14, // Font.BOLDITALIC,java.awt.Color.blue))); headerFoter.setAlignment(com.lowagie.text.HeaderFooter.ALIGN_CENTER); docPdf.setHeader(headerFoter); } catch (java.sql.SQLException SqlExec) { javax.swing.JOptionPane.showMessageDialog( new javax.swing.JFrame(), SqlExec.getMessage()); } com.lowagie.text.HeaderFooter footer = new com.lowagie.text.HeaderFooter( new Phrase("Price List - Page: "), true); // FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 12, // Font.BOLDITALIC,java.awt.Color.blue)); docPdf.setFooter(footer); docPdf.open(); try { com.lowagie.text.pdf.PdfPTable table = new com.lowagie.text.pdf.PdfPTable(5); int headerwidths[] = {20, 50, 30, 30, 30}; table.setWidths(headerwidths); table.setWidthPercentage((100)); // table.setHeaderRows(2); table .getDefaultCell() .setBorder(Rectangle.BOTTOM | Rectangle.TOP | Rectangle.LEFT | Rectangle.RIGHT); table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER); Phrase phrase = new Phrase(" "); // table.addCell(phrase); try { table.getDefaultCell().setColspan(5); phrase = new Phrase("Departmental Price List "); table.addCell(phrase); table.getDefaultCell().setColspan(4); java.sql.Statement st2 = connectDB.createStatement(); // java.sql.ResultSet rset = st.executeQuery("select code,upper(service_type) as // description,rate from pricelist WHERE main_service ilike '"+bank+"%' order by // service_type");// tn,debit_note db WHERE tn.policy_no != '' and tn.policy_no = // db.policy_no GROUP BY tn.policy_no,db.policy_class"); System.out.println("Printing Price List for GL/CODE : [" + bank + "]"); java.sql.ResultSet rset3 = st2.executeQuery( "SELECT DISTINCT activity FROM pb_activity WHERE code ILIKE '" + bank + "'"); while (rset3.next()) { table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT); phrase = new Phrase( rset3.getString(1).toUpperCase() + " - " + bank + " Price List as at : " + date, pFontHeader); table.addCell(phrase); } // Phrase phrase = new Phrase(bank +" Balance Report" +" as at : " +endDate, // pFontHeader); // table.addCell(phrase); table.getDefaultCell().setColspan(1); table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT); phrase = new Phrase("Printed on : " + date, pFontHeader); table.addCell(phrase); table.getDefaultCell().setColspan(1); // table.getDefaultCell().setBackgroundColor(java.awt.Color.LIGHT_GRAY); table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT); phrase = new Phrase("CODE", pFontHeader); table.addCell(phrase); // table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER); phrase = new Phrase("DESCRIPTION", pFontHeader); table.addCell(phrase); table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT); // phrase = new Phrase("",pFontHeader); // table.addCell(phrase); phrase = new Phrase("Norminal Rate (E.A) " + ks, pFontHeader); table.addCell(phrase); phrase = new Phrase("Special Rate (PRIVATE) " + ks, pFontHeader); table.addCell(phrase); phrase = new Phrase("NON E.A " + ks, pFontHeader); table.addCell(phrase); // phrase = new Phrase("Credit KShs.",pFontHeader); // table.addCell(phrase); // table.getDefaultCell().setBackgroundColor(java.awt.Color.WHITE); // table.getDefaultCell().setBorderColor(java.awt.Color.WHITE); double osBalance = 0.00; // java.sql.Connection conDb1 = // java.sql.DriverManager.getConnection("jdbc:postgresql://localhost:5432/sako","postgres","pilsiner"); java.sql.Statement st = connectDB.createStatement(); // java.sql.Statement st2 = connectDB.createStatement(); // java.sql.ResultSet rset = st.executeQuery("select code,upper(service_type) as // description,rate from pricelist WHERE main_service ilike '"+bank+"%' order by // service_type");// tn,debit_note db WHERE tn.policy_no != '' and tn.policy_no = // db.policy_no GROUP BY tn.policy_no,db.policy_class"); System.out.println("Printing Price List for GL/CODE : [" + bank + "]"); java.sql.ResultSet rset = st.executeQuery( "SELECT code, upper(service_type), rate, anaesthetist_rate,other_prices FROM pb_operating_parameters WHERE gl_account ilike '" + bank + "' order by service_type"); while (rset.next()) { table.getDefaultCell().setColspan(1); table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT); phrase = new Phrase(dbObject.getDBObject(rset.getObject(1), "-"), pFontHeader1); table.addCell(phrase); table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT); // table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT); phrase = new Phrase(dbObject.getDBObject(rset.getObject(2), "-"), pFontHeader1); table.addCell(phrase); // table.addCell(phrase); table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT); phrase = new Phrase( new com.afrisoftech.sys.Format2Currency() .Format2Currency(rset.getString(3)), pFontHeader); // osBalance = osBalance + rset1.getDouble(6); table.addCell(phrase); table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT); phrase = new Phrase( new com.afrisoftech.sys.Format2Currency() .Format2Currency(rset.getString(4)), pFontHeader); // osBalance = osBalance + rset1.getDouble(6); table.addCell(phrase); phrase = new Phrase( new com.afrisoftech.sys.Format2Currency() .Format2Currency(rset.getString(5)), pFontHeader); // osBalance = osBalance + rset1.getDouble(6); table.addCell(phrase); } docPdf.add(table); } catch (java.sql.SQLException SqlExec) { javax.swing.JOptionPane.showMessageDialog( new javax.swing.JFrame(), SqlExec.getMessage()); } } catch (com.lowagie.text.BadElementException BadElExec) { javax.swing.JOptionPane.showMessageDialog( new javax.swing.JFrame(), BadElExec.getMessage()); } } catch (java.io.FileNotFoundException fnfExec) { javax.swing.JOptionPane.showMessageDialog(new javax.swing.JFrame(), fnfExec.getMessage()); } } catch (com.lowagie.text.DocumentException lwDocexec) { javax.swing.JOptionPane.showMessageDialog(new javax.swing.JFrame(), lwDocexec.getMessage()); } docPdf.close(); docPdf.close(); com.afrisoftech.lib.PDFRenderer.renderPDF(tempFile); } catch (java.io.IOException IOexec) { javax.swing.JOptionPane.showMessageDialog(new javax.swing.JFrame(), IOexec.getMessage()); } }
public void toPDFGraphicFile(File file, int width, int height) throws IOException { // otherwise toolbar appears plotToolBar.setVisible(false); com.lowagie.text.Document document = new com.lowagie.text.Document(); document.setPageSize(new Rectangle(width, height)); FileOutputStream fos = new FileOutputStream(file); PdfWriter writer = null; try { writer = PdfWriter.getInstance(document, fos); } catch (DocumentException ex) { Logger.getLogger(PlotPanel.class.getName()).log(Level.SEVERE, null, ex); } document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(width, height); Graphics2D g2d = tp.createGraphics(width, height); Image image = createImage(getWidth(), getHeight()); paint(image.getGraphics()); image = new ImageIcon(image).getImage(); g2d.drawImage(image, 0, 0, Color.WHITE, null); g2d.dispose(); cb.addTemplate(tp, 1, 0, 0, 1, 0, 0); document.close(); // make it reappear plotToolBar.setVisible(true); }
public void beginDraw() { // long t0 = System.currentTimeMillis(); if (document == null) { document = new Document(new Rectangle(width, height)); try { if (file != null) { // BufferedOutputStream output = new BufferedOutputStream(stream, 16384); output = new BufferedOutputStream(new FileOutputStream(file), 16384); } else if (output == null) { throw new RuntimeException( "PGraphicsPDF requires a path " + "for the location of the output file."); } writer = PdfWriter.getInstance(document, output); document.open(); content = writer.getDirectContent(); // template = content.createTemplate(width, height); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Problem saving the PDF file."); } // System.out.println("beginDraw fonts " + (System.currentTimeMillis() - t)); g2 = content.createGraphics(width, height, getMapper()); // g2 = template.createGraphics(width, height, mapper); } // System.out.println("beginDraw " + (System.currentTimeMillis() - t0)); super.beginDraw(); }
/** * @param index * @throws DocumentException * @throws IOException */ public PdfHDPageWrapper(int index) throws DocumentException, IOException { // Read settings. // '_' - prefix for for temp file. After stamping file would be renamed outputFileName = "_" + index + WikiSettings.getInstance().getOutputFileName(); // 72 pixels per inch // pdfDocument = new Document(new Rectangle(432, 648));//6" x 9" pdfDocument = new Document(new Rectangle(1918, 1018)); // // pdfDocument.setMargins(32, 32, 0, 32); pdfDocument.setMargins(32, 32, -565, 32); pdfWriter = PdfWriter.getInstance( pdfDocument, new FileOutputStream( WikiSettings.getInstance().getOutputFolder() + "/" + outputFileName)); // header = new PageHeaderEvent(0); // pdfWriter.setPageEvent(header); pdfDocument.open(); // pdfDocument.setMarginMirroring(true); _wikiFontSelector = new WikiFontSelector(); // PdfContentByte cb = pdfWriter.getDirectContent(); // ColumnText ct = new ColumnText(cb); openMultiColumn(); }
/** * An example using MultiColumnText with irregular columns. * * @param args no arguments needed */ public static void main(String[] args) { System.out.println("Simple MultiColumnText"); try { Document document = new Document(); OutputStream out = new FileOutputStream("multicolumnsimple.pdf"); PdfWriter.getInstance(document, out); document.open(); MultiColumnText mct = new MultiColumnText(); // set up 3 even columns with 10pt space between mct.addRegularColumns(document.left(), document.right(), 10f, 3); // Write some iText poems for (int i = 0; i < 30; i++) { mct.addElement(new Paragraph(String.valueOf(i + 1))); mct.addElement(newPara(randomWord(noun), Element.ALIGN_CENTER, Font.BOLDITALIC)); for (int j = 0; j < 4; j++) { mct.addElement(newPara(poemLine(), Element.ALIGN_LEFT, Font.NORMAL)); } mct.addElement(newPara(randomWord(adverb), Element.ALIGN_LEFT, Font.NORMAL)); mct.addElement(newPara("\n\n", Element.ALIGN_LEFT, Font.NORMAL)); } document.add(mct); document.close(); } catch (DocumentException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } }
public static void main(String[] args) throws Exception { Document doc = new Document(); PdfWriter.getInstance(doc, new FileOutputStream("htmlToPdfAuto.pdf")); doc.open(); HtmlParser.parse( doc, new InputSource(HtmlToPdfAuto.class.getResourceAsStream("/htmlToPdfSaxAuto.html"))); doc.close(); }
/** * Generates simple PDF, RTF and HTML files using only one Document object. * * @param args no arguments needed here */ public static void main(String[] args) { System.out.println("Hello World in PDF, RTF and HTML"); // step 1: creation of a document-object Document document = new Document(); try { // step 2: // we create 3 different writers that listen to the document File file1 = new File("HelloWorldPdf.pdf"); File file2 = new File("HelloWorldRtf.rtf"); File file3 = new File("HelloWorldHtml.html"); if (!file1.exists()) { file1.canWrite(); } if (!file2.exists()) { file2.canWrite(); } if (!file3.exists()) { file3.canWrite(); } PdfWriter pdf = PdfWriter.getInstance(document, new FileOutputStream(file1)); RtfWriter2 rtf = RtfWriter2.getInstance(document, new FileOutputStream(file2)); HtmlWriter.getInstance(document, new FileOutputStream(file3)); // step 3: we open the document document.open(); // step 4: we add a paragraph to the document document.add(new Paragraph("Hello World")); // we make references Anchor pdfRef = new Anchor("see Hello World in PDF."); pdfRef.setReference("./HelloWorldPdf.pdf"); Anchor rtfRef = new Anchor("see Hello World in RTF."); rtfRef.setReference("./HelloWorldRtf.rtf"); // we add the references, but only to the HTML page: pdf.pause(); rtf.pause(); document.add(pdfRef); document.add(Chunk.NEWLINE); document.add(rtfRef); pdf.resume(); rtf.resume(); } catch (DocumentException de) { System.err.println(de.getMessage()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); } // step 5: we close the document document.close(); }
private boolean txt2Pdf(File inputFile, File outputFile, Charset inputFileCharset) { // // ๅ ๅฐtxt่ฝฌๆodt // String fileName = inputFile.getAbsolutePath(); // if (fileName.endsWith(".txt")) { BufferedReader bufferedReader = null; try { // ๅคๆญๅๅงtxtๆไปถ็็ผ็ ๆ ผๅผ๏ผ่ทๅๅๅบ็ๆไปถ่ฏปๅ ฅ bufferedReader = new BufferedReader( new InputStreamReader(new FileInputStream(inputFile), inputFileCharset)); // ๅฐtxtๅ ๅฎน็ดๆฅ็ๆpdf Document document = new Document(); BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); Font font_normal = new Font(bfChinese, 10, Font.NORMAL); // ่ฎพ็ฝฎๅญไฝๅคงๅฐ document.setPageSize(PageSize.A4); // ่ฎพ็ฝฎ้กต้ขๅคงๅฐ if (!outputFile.exists()) { outputFile.createNewFile(); } try { PdfWriter.getInstance(document, new FileOutputStream(outputFile)); document.open(); } catch (Exception e) { e.printStackTrace(); } String content = null; while ((content = bufferedReader.readLine()) != null) { document.add(new Paragraph(content, font_normal)); } document.close(); bufferedReader.close(); return true; } catch (ConnectException cex) { cex.printStackTrace(); // System.out.println("่ฝฌๆขๅคฑ่ดฅ๏ผ"); return false; } catch (FileNotFoundException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } catch (DocumentException e) { e.printStackTrace(); return false; } finally { // close the connection if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } } // } }
public static void main(String[] args) throws Exception { Document doc = new Document(); PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream("unsigned_signature_field.pdf")); doc.open(); doc.add(new Paragraph("Hello world with digital signature block.")); PdfAcroForm acroForm = writer.getAcroForm(); acroForm.addSignature("sig", 73, 705, 149, 759); doc.close(); }
/** * Generates a PDF file with the text 'Hello World' * * @param args no arguments needed here */ public static byte[] getDashboardPDFAsByteArray() { String localProviderURL = "t3://localhost:7001"; System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory"); System.setProperty(Context.PROVIDER_URL, localProviderURL); System.out.println("Generating VINSight DashBoard Reports"); // step 1: creation of a document-object Document document = new Document(); ByteArrayOutputStream baos = new ByteArrayOutputStream(100000); try { // step 2 PdfWriter writer; writer = PdfWriter.getInstance(document, baos); // step 3 document.open(); // step 4: we add a paragraph to the document document.add(new Paragraph("VINSight Health Check")); document.add(new Paragraph("Report 1")); // create the chart1 image JFreeChart chart1 = VINSightDashboardReport.createVINSightDashBoardChart1(); BufferedImage image1 = chart1.createBufferedImage(350, 350); image1.flush(); document.add(com.lowagie.text.Image.getInstance(image1, null)); document.add(new Paragraph("Report 2")); JFreeChart chart2 = VINSightDashboardReport.createVINSightDashBoardChart2(); BufferedImage image2 = chart2.createBufferedImage(350, 350); image2.flush(); document.add(com.lowagie.text.Image.getInstance(image2, null)); } catch (DocumentException de) { de.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { // step 5 document.close(); try { baos.close(); } catch (IOException ioe) { /*ignore*/ } } return baos.toByteArray(); }
/** * Creates a document with some goto actions. * * @param args no arguments needed */ public static void main(String[] args) { System.out.println("Destinations"); // step 1: creation of a document-object Document document = new Document(); try { // step 2: PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("Destinations.pdf")); // step 3: writer.setViewerPreferences(PdfWriter.PageModeUseOutlines); document.open(); // step 4: we grab the ContentByte and do some stuff with it PdfContentByte cb = writer.getDirectContent(); // we create a PdfTemplate PdfTemplate template = cb.createTemplate(25, 25); // we add some crosses to visualize the destinations template.moveTo(13, 0); template.lineTo(13, 25); template.moveTo(0, 13); template.lineTo(50, 13); template.stroke(); // we add the template on different positions cb.addTemplate(template, 287, 787); cb.addTemplate(template, 187, 487); cb.addTemplate(template, 487, 287); cb.addTemplate(template, 87, 87); // we define the destinations PdfDestination d1 = new PdfDestination(PdfDestination.XYZ, 300, 800, 0); PdfDestination d2 = new PdfDestination(PdfDestination.FITH, 500); PdfDestination d3 = new PdfDestination(PdfDestination.FITR, 200, 300, 400, 500); PdfDestination d4 = new PdfDestination(PdfDestination.FITBV, 100); PdfDestination d5 = new PdfDestination(PdfDestination.FIT); // we define the outlines PdfOutline out1 = new PdfOutline(cb.getRootOutline(), d1, "root"); PdfOutline out2 = new PdfOutline(out1, d2, "sub 1"); new PdfOutline(out1, d3, "sub 2"); new PdfOutline(out2, d4, "sub 2.1"); new PdfOutline(out2, d5, "sub 2.2"); } catch (Exception de) { de.printStackTrace(); } // step 5: we close the document document.close(); }
public AbstractPDFGenerator(final OutputStream out, final String type) { this.out = out; try { if (type != null && "landscape".equalsIgnoreCase(type)) document = new Document(PageSize.A4.rotate()); else document = new Document(); PdfWriter.getInstance(document, out); document.open(); } catch (final Exception e) { throw new ApplicationRuntimeException("estimate.pdf.error", e); } }
/** * Creates a document. * * @param outputStream The output stream to write the document content. * @param pageSize the page size. * @return A Document. */ public static Document openDocument(OutputStream outputStream, Rectangle pageSize) { try { Document document = new Document(pageSize); PdfWriter.getInstance(document, outputStream); document.open(); return document; } catch (DocumentException ex) { throw new RuntimeException("Failed to open PDF document", ex); } }
public void exportGraphic(Picture picture, OutputStream out) throws IOException { int width = picture.getPictureWidth(); int height = picture.getPictureHeight(); Document doc = new Document(new com.lowagie.text.Rectangle(width, height)); try { PdfWriter pWriter = PdfWriter.getInstance(doc, out); doc.open(); Graphics2D g = pWriter.getDirectContent().createGraphics(width, height); picture.paintPicture(g); g.dispose(); doc.close(); } catch (DocumentException e) { throw (IOException) new IOException(e.getMessage()).initCause(e); } }
/** * Invokes the createPOQuotePDF method to create a purchase order quote pdf document and saves it * into a file which name and location are specified in the pdfParameters. * * @param po The PurchaseOrderDocument to be used to generate the pdf. * @param poqv The PurchaseOrderVendorQuote to be used to generate the pdf. * @param pdfFileLocation The location to save the pdf file. * @param pdfFilename The name for the pdf file. * @param campusName The campus name to be used to generate the pdf. * @param contractManagerCampusCode The contract manager campus code to be used to generate the * pdf. * @param logoImage The logo image file name to be used to generate the pdf. * @param environment The current environment used (e.g. DEV if it is a development environment). */ public void savePOQuotePDF( PurchaseOrderDocument po, PurchaseOrderVendorQuote poqv, PurchaseOrderParameters transmitParameters, String environment) { if (LOG.isDebugEnabled()) { LOG.debug("savePOQuotePDF() started for po number " + po.getPurapDocumentIdentifier()); } try { PurchaseOrderTransmitParameters orderTransmitParameters = (PurchaseOrderTransmitParameters) transmitParameters; CampusParameter deliveryCampus = orderTransmitParameters.getCampusParameter(); if (deliveryCampus == null) { throw new RuntimeException(" delivery campus is null"); } String campusName = deliveryCampus.getCampus().getName(); if (campusName == null) { throw new RuntimeException("Campus Information is missing - campusName: " + campusName); } Document doc = this.getDocument(9, 9, 70, 36); PdfWriter writer = PdfWriter.getInstance( doc, new FileOutputStream( orderTransmitParameters.getPdfFileLocation() + orderTransmitParameters.getPdfFileName())); this.createPOQuotePdf( po, poqv, campusName, orderTransmitParameters.getContractManagerCampusCode(), orderTransmitParameters.getLogoImage(), doc, writer, environment); } catch (DocumentException de) { LOG.error(de.getMessage(), de); throw new PurError("Document Exception when trying to save a Purchase Order Quote PDF", de); } catch (FileNotFoundException f) { LOG.error(f.getMessage(), f); throw new PurError( "FileNotFound Exception when trying to save a Purchase Order Quote PDF", f); } }
public void manipulatePdf(String src, String dest, int pow) throws IOException, DocumentException { PdfReader reader = new PdfReader(src); Rectangle pageSize = reader.getPageSize(1); Rectangle newSize = (pow % 2) == 0 ? new Rectangle(pageSize.getWidth(), pageSize.getHeight()) : new Rectangle(pageSize.getHeight(), pageSize.getWidth()); Rectangle unitSize = new Rectangle(pageSize.getWidth(), pageSize.getHeight()); for (int i = 0; i < pow; i++) { unitSize = new Rectangle(unitSize.getHeight() / 2, unitSize.getWidth()); } int n = (int) Math.pow(2, pow); int r = (int) Math.pow(2, pow / 2); int c = n / r; Document document = new Document(newSize, 0, 0, 0, 0); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(String.format(dest, n))); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfImportedPage page; Rectangle currentSize; float offsetX, offsetY, factor; int total = reader.getNumberOfPages(); for (int i = 0; i < total; ) { if (i % n == 0) { document.newPage(); } currentSize = reader.getPageSize(++i); factor = Math.min( unitSize.getWidth() / currentSize.getWidth(), unitSize.getHeight() / currentSize.getHeight()); offsetX = unitSize.getWidth() * ((i % n) % c) + (unitSize.getWidth() - (currentSize.getWidth() * factor)) / 2f; offsetY = newSize.getHeight() - (unitSize.getHeight() * (((i % n) / c) + 1)) + (unitSize.getHeight() - (currentSize.getHeight() * factor)) / 2f; page = writer.getImportedPage(reader, i); cb.addTemplate(page, factor, 0, 0, factor, offsetX, offsetY); } document.close(); }
private ByteArrayOutputStream getPdfData( JSONArray data, JSONArray res, HttpServletRequest request) throws ServiceException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { String[] colHeader = getColHeader(); String[] colIndex = getColIndexes(); String[] val = getColValues(colHeader, data); String[] resources = getResourcesColHeader(res, data); String[] mainHeader = {"Dates", "Duration", "Work", "Cost", "Tasks", "Resources"}; Document document = null; if (landscape) { Rectangle recPage = new Rectangle(PageSize.A4.rotate()); recPage.setBackgroundColor(new java.awt.Color(255, 255, 255)); document = new Document(recPage, 15, 15, 30, 30); } else { Rectangle recPage = new Rectangle(PageSize.A4); recPage.setBackgroundColor(new java.awt.Color(255, 255, 255)); document = new Document(recPage, 15, 15, 30, 30); } PdfWriter writer = PdfWriter.getInstance(document, baos); writer.setPageEvent(new EndPage()); document.open(); if (showLogo) { getCompanyDetails(request); addComponyLogo(document, request); } addTitleSubtitle(document); addTable(data, resources, colIndex, colHeader, mainHeader, val, document); document.close(); writer.close(); baos.close(); } catch (ConfigurationException ex) { throw ServiceException.FAILURE("ExportProjectReport.getPdfData", ex); } catch (DocumentException ex) { throw ServiceException.FAILURE("ExportProjectReport.getPdfData", ex); } catch (JSONException e) { throw ServiceException.FAILURE("ExportProjectReport.getPdfData", e); } catch (IOException e) { throw ServiceException.FAILURE("ExportProjectReport.getPdfData", e); } catch (Exception e) { throw ServiceException.FAILURE("ExportProjectReport.getPdfData", e); } return baos; }
/** * Writing vertical text. * * @param args no arguments needed */ public static void main(String[] args) { Document document = new Document(PageSize.A4, 50, 50, 50, 50); try { texts[3] = convertCid(texts[0]); texts[4] = convertCid(texts[1]); texts[5] = convertCid(texts[2]); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("vertical.pdf")); int idx = 0; document.open(); PdfContentByte cb = writer.getDirectContent(); for (int j = 0; j < 2; ++j) { BaseFont bf = BaseFont.createFont("KozMinPro-Regular", encs[j], false); cb.setRGBColorStroke(255, 0, 0); cb.setLineWidth(0); float x = 400; float y = 700; float height = 400; float leading = 30; int maxLines = 6; for (int k = 0; k < maxLines; ++k) { cb.moveTo(x - k * leading, y); cb.lineTo(x - k * leading, y - height); } cb.rectangle(x, y, -leading * (maxLines - 1), -height); cb.stroke(); int status; VerticalText vt = new VerticalText(cb); vt.setVerticalLayout(x, y, height, maxLines, leading); vt.addText(new Chunk(texts[idx++], new Font(bf, 20))); vt.addText(new Chunk(texts[idx++], new Font(bf, 20, 0, Color.blue))); status = vt.go(); System.out.println(status); vt.setAlignment(Element.ALIGN_RIGHT); vt.addText(new Chunk(texts[idx++], new Font(bf, 20, 0, Color.orange))); status = vt.go(); System.out.println(status); document.newPage(); } document.close(); } catch (Exception de) { de.printStackTrace(); } }
/** @see com.lowagie.toolbox.AbstractTool#execute() */ public void execute() { try { if (getValue("odd") == null) throw new InstantiationException("You need to choose a sourcefile for the odd pages"); File odd_file = (File) getValue("odd"); if (getValue("even") == null) throw new InstantiationException("You need to choose a sourcefile for the even pages"); File even_file = (File) getValue("even"); if (getValue("destfile") == null) throw new InstantiationException("You need to choose a destination file"); File pdf_file = (File) getValue("destfile"); RandomAccessFileOrArray odd = new RandomAccessFileOrArray(odd_file.getAbsolutePath()); RandomAccessFileOrArray even = new RandomAccessFileOrArray(even_file.getAbsolutePath()); Image img = TiffImage.getTiffImage(odd, 1); Document document = new Document(new Rectangle(img.getScaledWidth(), img.getScaledHeight())); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdf_file)); document.open(); PdfContentByte cb = writer.getDirectContent(); int count = Math.max(TiffImage.getNumberOfPages(odd), TiffImage.getNumberOfPages(even)); for (int c = 0; c < count; ++c) { try { Image imgOdd = TiffImage.getTiffImage(odd, c + 1); Image imgEven = TiffImage.getTiffImage(even, count - c); document.setPageSize(new Rectangle(imgOdd.getScaledWidth(), imgOdd.getScaledHeight())); document.newPage(); imgOdd.setAbsolutePosition(0, 0); cb.addImage(imgOdd); document.setPageSize(new Rectangle(imgEven.getScaledWidth(), imgEven.getScaledHeight())); document.newPage(); imgEven.setAbsolutePosition(0, 0); cb.addImage(imgEven); } catch (Exception e) { System.out.println("Exception page " + (c + 1) + " " + e.getMessage()); } } odd.close(); even.close(); document.close(); } catch (Exception e) { e.printStackTrace(); } }
public static void exportAsPdf( List<EventoBean> eventi, ByteArrayOutputStream baos, IEventiService eventiService) throws DocumentException, UtilsException { Document document = new Document(); PdfWriter.getInstance(document, baos); document.open(); addMetaData(document); addTitlePage(document); // Start a new page document.newPage(); addContent(document, eventi, eventiService); document.close(); }
/* * crea un file pdf contenente lo stack trace dell'eccezione */ private void createErrorFile(String url, File outputFile, Exception exception) { Document document = new Document(); PdfWriter pdfwriter = null; try { pdfwriter = PdfWriter.getInstance(document, new FileOutputStream(outputFile)); document.open(); StringBuilder buffer = new StringBuilder("Non รจ stato possibile generare"); buffer.append(" il file pdf per l'URL\n\n"); buffer.append(url); buffer.append("\n\na causa del seguente errore:\n\n"); document.add(new Paragraph(buffer.toString())); StringWriter stringWriter = new StringWriter(); exception.printStackTrace(new PrintWriter(stringWriter)); document.add(new Paragraph(stringWriter.toString())); document.close(); pdfwriter.close(); } catch (FileNotFoundException | DocumentException e) { log.error("errore di scrittura del file di errore", e); } }
public void pv() { try { Document document = new Document(PageSize.A4, 36, 72, 108, 180); PdfWriter.getInstance(document, new FileOutputStream("pdfFile.pdf")); File f = new File("abc.txt"); FileReader fr = new FileReader(f); BufferedReader br = new BufferedReader(fr); String i; while ((i = br.readLine()) != null) { document.open(); document.add(new Paragraph(i)); } System.out.println("fetched database is inserted into pdf file"); document.close(); } catch (Exception e) { } }
private PdfWorksheet(OutputStream out, Collection<SubjectArea> subjectAreas, String courseNumber) throws IOException, DocumentException { iUseCommitedAssignments = ApplicationProperty.WorksheetPdfUseCommittedAssignments.isTrue(); iSubjectAreas = new TreeSet<SubjectArea>( new Comparator<SubjectArea>() { @Override public int compare(SubjectArea s1, SubjectArea s2) { return s1.getSubjectAreaAbbreviation().compareTo(s2.getSubjectAreaAbbreviation()); } }); iSubjectAreas.addAll(subjectAreas); iCourseNumber = courseNumber; if (iCourseNumber != null && (iCourseNumber.trim().length() == 0 || "*".equals(iCourseNumber.trim().length()))) iCourseNumber = null; iDoc = new Document(PageSize.LETTER.rotate()); iOut = out; PdfWriter.getInstance(iDoc, iOut); String session = null; String subjects = ""; for (SubjectArea sa : iSubjectAreas) { if (subjects.isEmpty()) subjects += ", "; subjects += sa.getSubjectAreaAbbreviation(); if (session == null) session += sa.getSession().getLabel(); } iDoc.addTitle(subjects + (iCourseNumber == null ? "" : " " + iCourseNumber) + " Worksheet"); iDoc.addAuthor( ApplicationProperty.WorksheetPdfAuthor.value().replace("%", Constants.getVersion())); iDoc.addSubject(subjects + (session == null ? "" : " -- " + session)); iDoc.addCreator("UniTime " + Constants.getVersion() + ", www.unitime.org"); if (!iSubjectAreas.isEmpty()) iCurrentSubjectArea = iSubjectAreas.first(); iDoc.open(); printHeader(); }
/** * @see org.kuali.kfs.module.bc.service.PayrateImportService#generatePdf(java.lang.StringBuilder, * java.io.ByteArrayOutputStream) */ @NonTransactional public void generatePdf(List<ExternalizedMessageWrapper> logMessages, ByteArrayOutputStream baos) throws DocumentException { Document document = new Document(); PdfWriter.getInstance(document, baos); document.open(); for (ExternalizedMessageWrapper messageWrapper : logMessages) { String message; if (messageWrapper.getParams().length == 0) message = SpringContext.getBean(KualiConfigurationService.class) .getPropertyString(messageWrapper.getMessageKey()); else { String temp = SpringContext.getBean(KualiConfigurationService.class) .getPropertyString(messageWrapper.getMessageKey()); message = MessageFormat.format(temp, (Object[]) messageWrapper.getParams()); } document.add(new Paragraph(message)); } document.close(); }
/** * This creates a file to capture the pdf output generated by calls to graphics2D (e.g., use * makeMap). This will overwrite an existing file. * * @param pageSize e.g, PageSize.LETTER or PageSize.LETTER.rotate() (or A4, or, ...) * @param width the bounding box width, in 1/144ths of an inch * @param height the bounding box height, in 1/144ths of an inch * @param outputStream * @return an object[] with 0=g2D, 1=document, 2=pdfContentByte, 3=pdfTemplate * @throws Exception if trouble */ public static Object[] createPdf( com.lowagie.text.Rectangle pageSize, int bbWidth, int bbHeight, OutputStream outputStream) throws Exception { // currently, this uses itext // see the sample program: // // file://localhost/C:/programs/iText/examples/com/lowagie/examples/directcontent/graphics2D/G2D.java // Document.compress = false; //for test purposes only Document document = new Document(pageSize); document.addCreationDate(); document.addCreator("gov.noaa.pfel.coastwatch.SgtUtil.createPdf"); document.setPageSize(pageSize); PdfWriter writer = PdfWriter.getInstance(document, outputStream); document.open(); // create contentByte and template and Graphics2D objects PdfContentByte pdfContentByte = writer.getDirectContent(); PdfTemplate pdfTemplate = pdfContentByte.createTemplate(bbWidth, bbHeight); Graphics2D g2D = pdfTemplate.createGraphics(bbWidth, bbHeight); return new Object[] {g2D, document, pdfContentByte, pdfTemplate}; }
/** * Generates the purchase order quote pdf document based on the data in the given input * parameters, creates a pdf writer using the given byteArrayOutputStream then write the pdf * document into the writer. * * @param po The PurchaseOrderDocument to be used to generate the pdf. * @param poqv The PurchaseOrderVendorQuote to be used to generate the pdf. * @param campusName The campus name to be used to generate the pdf. * @param contractManagerCampusCode The contract manager campus code to be used to generate the * pdf. * @param logoImage The logo image file name to be used to generate the pdf. * @param byteArrayOutputStream The ByteArrayOutputStream to print the pdf to. * @param environment The current environment used (e.g. DEV if it is a development environment). */ public void generatePOQuotePDF( PurchaseOrderDocument po, PurchaseOrderVendorQuote poqv, String campusName, String contractManagerCampusCode, String logoImage, ByteArrayOutputStream byteArrayOutputStream, String environment) { if (LOG.isDebugEnabled()) { LOG.debug("generatePOQuotePDF() started for po number " + po.getPurapDocumentIdentifier()); } Collection errors = new ArrayList(); try { Document doc = getDocument(9, 9, 70, 36); PdfWriter writer = PdfWriter.getInstance(doc, byteArrayOutputStream); this.createPOQuotePdf( po, poqv, campusName, contractManagerCampusCode, logoImage, doc, writer, environment); } catch (DocumentException de) { LOG.error(de.getMessage(), de); throw new PurError("Document Exception when trying to save a Purchase Order Quote PDF", de); } }
/** * Performs the action: generate a PDF from a GET or POST. * * @param request the Servlets request object * @param response the Servlets request object * @param methodGetPost the method that was used in the form */ public void makePdf( HttpServletRequest request, HttpServletResponse response, String methodGetPost) { try { // take the message from the URL or create default message String msg = request.getParameter("msg"); if (msg == null || msg.trim().length() <= 0) msg = "[ specify a message in the 'msg' argument on the URL ]"; // create simple doc and write to a ByteArrayOutputStream Document document = new Document(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter.getInstance(document, baos); document.open(); document.add(new Paragraph(msg)); document.add(Chunk.NEWLINE); document.add(new Paragraph("The method used to generate this PDF was: " + methodGetPost)); document.close(); // setting some response headers response.setHeader("Expires", "0"); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); response.setHeader("Pragma", "public"); // setting the content type response.setContentType("application/pdf"); // the contentlength is needed for MSIE!!! response.setContentLength(baos.size()); // write ByteArrayOutputStream to the ServletOutputStream ServletOutputStream out = response.getOutputStream(); baos.writeTo(out); out.flush(); } catch (Exception e2) { System.out.println("Error in " + getClass().getName() + "\n" + e2); } }
private void print() { Document document = new Document(PageSize.A4.rotate()); try { PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("jTable.pdf")); document.open(); PdfContentByte cb = writer.getDirectContent(); cb.saveState(); Graphics2D g2 = cb.createGraphicsShapes(500, 500); Shape oldClip = g2.getClip(); g2.clipRect(0, 0, 500, 500); table.print(g2); g2.setClip(oldClip); g2.dispose(); cb.restoreState(); } catch (Exception e) { System.err.println(e.getMessage()); } document.close(); }
public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { Document document = new Document(); try { // OutputStream file = new FileOutputStream(new File("D:\\Test.pdf")); response.setContentType("application/pdf"); // PdfWriter.getInstance(document, file); PdfWriter.getInstance(document, response.getOutputStream()); document.open(); document.add(new Paragraph("Hello Sasi")); document.add(new Paragraph(new Date().toString())); // file.close(); } catch (Exception e) { e.printStackTrace(); } document.close(); return null; }
public ByteArrayOutputStream getReportCode() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Document document = new Document(PageSize.B4, 40, 200, 120, 20); try { PdfWriter writer = PdfWriter.getInstance(document, baos); MyPageEvents events = new MyPageEvents(); writer.setPageEvent(events); document.open(); if (data.size() == 0) { PdfPTable table = new PdfPTable(1); table.addCell(printStr("", 6, 8, false, PdfPCell.NO_BORDER, 0)); document.add(table); } PdfPTable table = new PdfPTable(1); table.setWidthPercentage(100); int border = 0; // Receipt Infos String row[] = (String[]) data.get(0); table.addCell(printStr("", 1, 18, false, border, 1)); table.addCell(printStr(row[17], 1, 22, false, border, 1)); table.addCell(printStr(" ", 1, 18, false, border, 1)); table.addCell(printStr(" ", 1, 18, false, border, 1)); table.addCell(printStr("Name: " + row[0], 1, 22, false, border, 0)); table.addCell(printStr(" " + row[13], 1, 22, false, border, 0)); table.addCell(printStr("Sex: " + row[14], 1, 22, false, border, 0)); table.addCell(printStr("DOB: " + row[15], 1, 22, false, border, 0)); if (row[12].equals("A")) table.addCell( printStr( "Nationality: " + GeneralDataInHtml.getCountryName(row[2]), 1, 22, false, border, 0)); table.addCell(printStr("PPT/Ref. No.: " + row[1], 1, 22, false, border, 0)); table.addCell(printStr(" ", 1, 18, false, border, 1)); table.addCell(printStr(" ", 1, 18, false, border, 1)); double cashTotal = 0; double chequeTotal = 0; table.addCell(printStr(row[3] + " x " + row[4] + " @$" + row[5], 1, 22, false, border, 0)); for (int i = 1; i < data.size(); i++) { String item[] = (String[]) data.get(i); table.addCell( printStr(item[3] + " x " + item[4] + " @$" + item[5], 1, 22, false, border, 0)); } table.addCell(printStr(" ", 1, 18, false, border, 1)); table.addCell(printStr(" ", 1, 18, false, border, 1)); double amt = Double.parseDouble(row[9]); if (row[7].equals("cash")) { table.addCell(printStr("Cash Total: HK$" + amt + "0", 1, 22, false, border, 0)); } else { table.addCell(printStr("Cheque: HK$" + amt + "0", 1, 22, false, border, 0)); table.addCell(printStr("--" + row[8], 1, 22, false, border, 0)); } table.addCell(printStr(" ", 1, 18, false, border, 1)); // Count Collection Date Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; int dayAdd = 2; int dayCount = 2; // int receiptDate = Integer.parseInt(row[18]); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); java.util.Date rDate = sdf.parse(row[18]); java.sql.Timestamp receiptDate = new java.sql.Timestamp(rDate.getTime()); // 86400000 milliseconds in a day long oneDay = 1 * 24 * 60 * 60 * 1000; try { conn = JdbcConnection.getConnection(); for (int k = 1; k <= dayCount; k++) { receiptDate.setTime(receiptDate.getTime() + oneDay); // System.out.println("select 1 from holiday where date = "+(receiptDate)); ps = conn.prepareStatement("select 1 from holiday where date = ?"); ps.setTimestamp(1, receiptDate); rs = ps.executeQuery(); if (rs.next()) { dayCount += 1; dayAdd += 1; } } } catch (Exception e) { e.printStackTrace(); } finally { if (rs != null) try { rs.close(); } catch (Exception e) { e.printStackTrace(); } if (ps != null) try { ps.close(); } catch (Exception e) { e.printStackTrace(); } if (conn != null) try { conn.close(); } catch (Exception e) { e.printStackTrace(); } } Calendar cal = Calendar.getInstance(); cal.set( Integer.parseInt(row[18].substring(0, 4)), Integer.parseInt(row[18].substring(4, 6)) - 1, Integer.parseInt(row[18].substring(6))); cal.add(cal.DATE, dayAdd); Date date = cal.getTime(); SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy (EEE)", Locale.US); table.addCell(printStr(" ", 1, 18, false, border, 1)); if (row[12].equals("A")) { table.addCell(printStr("Collection Date: " + df.format(date), 1, 22, false, border, 1)); table.addCell(printStr("Collection Time: 4:00pm to 5:00pm", 1, 22, false, border, 1)); table.addCell(printStr(" ", 1, 22, false, border, 1)); table.addCell(printStr(row[10] + " " + row[16], 1, 22, false, border, 1)); table.addCell(printStr(" ", 1, 22, false, border, 1)); table.addCell( printStr( "APPLICATION IS SUBJECTED TO APPROVAL, PLEASE BRING THIS RECEIPT ON COLLECTION DAY", 1, 22, false, border, 1)); table.addCell(printStr(row[11], 1, 32, false, border, 1)); table.addCell(printStr("(" + this.params + ")", 1, 22, false, border, 2)); } else { table.addCell(printStr("THANK YOU", 1, 22, false, border, 1)); table.addCell(printStr(row[10] + " " + row[16], 1, 22, false, border, 1)); table.addCell(printStr(" ", 1, 22, false, border, 1)); table.addCell(printStr(row[11], 1, 22, false, border, 1)); table.addCell(printStr("(" + this.params + ")", 1, 22, false, border, 2)); } float[] widths4 = {10}; table.setWidths(widths4); document.add(table); document.close(); } catch (Exception e) { e.printStackTrace(); } return baos; }