List of usage examples for com.lowagie.text Document close
boolean close
To view the source code for com.lowagie.text Document close.
Click Source Link
From source file:bucks.RedeemInvoice.java
License:Open Source License
void generateInvoice(HttpServletResponse res, Redeem redeem) { ////from w w w .j a va 2 s .com // paper size legal (A4) 8.5 x 11 // page 1-inch = 72 points // String spacer = " \n"; User user = redeem.getUser(); Vendor vendor = redeem.getVendor(); List<Buck> bk_bucks = redeem.getBk_bucks(); List<Buck> gc5_bucks = redeem.getGc5_bucks(); List<Buck> gc20_bucks = redeem.getGc20_bucks(); List<Buck> gc_bucks = redeem.getGc_bucks(); List<Dispute> disputes = redeem.getDisputes(); int bk_total = 0, gc5_total = 0, gc20_total = 0, total = 0; if (bk_bucks.size() > 0) { bk_total = bk_bucks.size() * 3; } if (gc5_bucks.size() > 0) { gc5_total = gc5_bucks.size() * 5; } if (gc20_bucks.size() > 0) { gc20_total = gc20_bucks.size() * 20; } total = bk_total + gc5_total + gc20_total; String vendor_name = ""; if (vendor != null) { vendor_name = vendor.getCleanName(); } ServletOutputStream out = null; String filename = "invoice_" + vendor_name + "_" + redeem.getId() + ".pdf"; try { // space // Rectangle pageSize = new Rectangle(612, 792); // 8.5" X 11" Document document = new Document(pageSize, 36, 36, 18, 18);// 18,18,54,35 ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter writer = PdfWriter.getInstance(document, baos); document.open(); Image image = Image.getInstance(imageUrl); // image = Image.getInstance(byte bytes[]);// generated image image.scalePercent(20f); Font fnt = new Font(Font.TIMES_ROMAN, 12, Font.NORMAL); Font fntb = new Font(Font.TIMES_ROMAN, 12, Font.BOLD); Font fntb2 = new Font(Font.TIMES_ROMAN, 14, Font.BOLD); // Phrase spacePhrase = new Phrase(); Chunk ch = new Chunk(spacer, fnt); spacePhrase.add(ch); float[] widths = { 15f, 85f }; // percentages PdfPTable headTable = new PdfPTable(widths); headTable.setWidthPercentage(100); headTable.getDefaultCell().setBorder(Rectangle.NO_BORDER); headTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); // image.setWidthPercentage(15.0f); PdfPCell cell = new PdfPCell(image); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_CENTER); // cell.setFixedHeight(46f); headTable.addCell(cell); Phrase phrase = new Phrase(); ch = new Chunk( "City of Bloomington Community Farmers Market\n Gift Certificates/Market Bucks Invoice\n ", fntb2); phrase.add(ch); Paragraph pp = new Paragraph(); pp.setIndentationLeft(20); pp.setAlignment(Element.ALIGN_LEFT); pp.add(phrase); cell = new PdfPCell(pp); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); headTable.addCell(cell); document.add(headTable); // float[] widths3 = { 50f, 50f }; // percentages PdfPTable table = new PdfPTable(widths3); table.setWidthPercentage(100); table.getDefaultCell().setBorder(Rectangle.NO_BORDER); table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); phrase = new Phrase(); ch = new Chunk(" Vendor Name: ", fntb); phrase.add(ch); ch = new Chunk(vendor.getFullName(), fnt); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_LEFT); cell.setBorder(Rectangle.NO_BORDER); table.addCell(cell); // phrase = new Phrase(); ch = new Chunk("Date: ", fntb); phrase.add(ch); ch = new Chunk(redeem.getDate(), fnt); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); cell.setBorder(Rectangle.NO_BORDER); table.addCell(cell); phrase = new Phrase(); ch = new Chunk(" Vendor Number: ", fntb); phrase.add(ch); ch = new Chunk(vendor.getId(), fnt); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_LEFT); cell.setBorder(Rectangle.NO_BORDER); table.addCell(cell); phrase = new Phrase(); // empty cell ch = new Chunk(" ", fntb); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_LEFT); cell.setBorder(Rectangle.NO_BORDER); table.addCell(cell); table.addCell(cell); // extra space table.addCell(cell); document.add(table); // phrase = new Phrase(new Chunk("\n", fnt)); document.add(phrase); // float[] widths2 = { 30f, 25f, 15f, 15f, 15f }; // percentages table = new PdfPTable(widths2); table.setWidthPercentage(90); // table.getDefaultCell().setBorder(Rectangle.NO_BORDER); table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE); // table.getDefaultCell().setPadding(5); phrase = new Phrase(); ch = new Chunk("Type of Voucher", fntb); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorderWidth(2f); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setPadding(4); cell.setLeading(2f, 1.2f); table.addCell(cell); // phrase = new Phrase(); ch = new Chunk("City Account Number", fntb); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorderWidth(2f); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setPadding(4); cell.setLeading(2f, 1.2f); table.addCell(cell); // phrase = new Phrase(); ch = new Chunk("Quantity", fntb); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorderWidth(2f); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setPadding(4); cell.setLeading(2f, 1.2f); table.addCell(cell); phrase = new Phrase(); ch = new Chunk("Multiply", fntb); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorderWidth(2f); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setPadding(4); cell.setLeading(2f, 1.2f); table.addCell(cell); phrase = new Phrase(); ch = new Chunk("Value", fntb); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorderWidth(2f); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_CENTER); cell.setPadding(4); cell.setLeading(2f, 1.2f); table.addCell(cell); // // second row phrase = new Phrase(); ch = new Chunk("Market Bucks", fnt); phrase.add(ch); cell = new PdfPCell(phrase); table.addCell(cell); // phrase = new Phrase(); ch = new Chunk("201-18-1865003-47240", fnt); phrase.add(ch); cell = new PdfPCell(phrase); table.addCell(cell); // phrase = new Phrase(); String str = " "; if (bk_bucks.size() > 0) { str = "" + bk_bucks.size(); } ch = new Chunk(str, fnt); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); cell.setVerticalAlignment(Element.ALIGN_CENTER); cell.setPadding(4); table.addCell(cell); phrase = new Phrase(); ch = new Chunk("x $3.00 = ", fnt); phrase.add(ch); cell = new PdfPCell(phrase); table.addCell(cell); phrase = new Phrase(); str = " "; if (bk_total > 0) { str = "$" + bk_total + ".00"; } ch = new Chunk(str, fnt); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); cell.setVerticalAlignment(Element.ALIGN_CENTER); cell.setPadding(4); table.addCell(cell); // // 3rd row phrase = new Phrase(); ch = new Chunk("$5 Gift Cerificates", fnt); phrase.add(ch); cell = new PdfPCell(phrase); table.addCell(cell); // phrase = new Phrase(); ch = new Chunk("201-18-1865003-47230", fnt); phrase.add(ch); cell = new PdfPCell(phrase); table.addCell(cell); // phrase = new Phrase(); str = " "; if (gc5_bucks.size() > 0) { str = "" + gc5_bucks.size(); } ch = new Chunk(str, fnt); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); cell.setVerticalAlignment(Element.ALIGN_CENTER); cell.setPadding(4); table.addCell(cell); phrase = new Phrase(); ch = new Chunk("x $5.00 = ", fnt); phrase.add(ch); cell = new PdfPCell(phrase); table.addCell(cell); phrase = new Phrase(); str = " "; if (gc5_total > 0) { str = "$" + gc5_total + ".00"; } ch = new Chunk(str, fnt); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); cell.setVerticalAlignment(Element.ALIGN_CENTER); cell.setPadding(4); table.addCell(cell); // // 4th row phrase = new Phrase(); ch = new Chunk("$20 Gift Certificates", fnt); phrase.add(ch); cell = new PdfPCell(phrase); table.addCell(cell); // phrase = new Phrase(); ch = new Chunk("201-18-1865003-47230", fnt); phrase.add(ch); cell = new PdfPCell(phrase); table.addCell(cell); // phrase = new Phrase(); str = " "; if (gc20_bucks.size() > 0) { str = "" + gc20_bucks.size(); } ch = new Chunk(str, fnt); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); cell.setVerticalAlignment(Element.ALIGN_CENTER); cell.setPadding(4); table.addCell(cell); phrase = new Phrase(); ch = new Chunk("x $20.00 = ", fnt); phrase.add(ch); cell = new PdfPCell(phrase); table.addCell(cell); str = " "; if (gc20_total > 0) { str = "$" + gc20_total + ".00"; } phrase = new Phrase(); ch = new Chunk(str, fnt); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); cell.setVerticalAlignment(Element.ALIGN_CENTER); cell.setPadding(4); table.addCell(cell); // // 5th row total phrase = new Phrase(); ch = new Chunk(" Total Value: ", fntb); phrase.add(ch); cell = new PdfPCell(phrase); cell.setColspan(4); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); cell.setVerticalAlignment(Element.ALIGN_CENTER); cell.setBorderWidth(2f); cell.setPadding(4); cell.setLeading(2f, 1.2f); table.addCell(cell); // phrase = new Phrase(); ch = new Chunk("$" + total + ".00", fntb); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); cell.setVerticalAlignment(Element.ALIGN_CENTER); cell.setBorderWidth(2f); cell.setPadding(4); cell.setLeading(2f, 1.2f); table.addCell(cell); document.add(table); // // float[] withs5 = { 100f }; table = new PdfPTable(withs5); table.setWidthPercentage(100); cell = new PdfPCell(new Phrase(" ")); cell.setBorder(Rectangle.BOTTOM); // cell.setBorderColorBottom(Color.BLACK); cell.setBorderWidthBottom(2f); table.addCell(cell); document.add(table); // ch = new Chunk("\n", fnt); phrase = new Phrase(); phrase.add(ch); document.add(phrase); // // float[] widths3 = {50f, 50f}; // percentages table = new PdfPTable(widths3); table.setWidthPercentage(100); // table.getDefaultCell().setBorder(Rectangle.NO_BORDER); table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); phrase = new Phrase(); ch = new Chunk(" Data Entry Completed by: ", fntb); phrase.add(ch); ch = new Chunk(user.getFullName(), fnt); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); // phrase = new Phrase(); ch = new Chunk(" Invoice Number: ", fntb); phrase.add(ch); ch = new Chunk(redeem.getId(), fnt); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); document.add(table); document.add(spacePhrase); document.add(spacePhrase); // // adding bucks and GC // float[] widths4 = { 100f }; // percentages table = new PdfPTable(widths4); table.setWidthPercentage(100); // table.getDefaultCell().setBorder(Rectangle.NO_BORDER); table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT); int row = 1, col = 1; if (bk_bucks.size() > 0) { phrase = new Phrase(); ch = new Chunk(" Market Bucks ", fntb); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setBorderWidth(2f); table.addCell(cell); phrase = new Phrase(); for (Buck one : bk_bucks) { ch = new Chunk("" + one.getId() + " ", fntb); phrase.add(ch); col++; if (col > 15) { row++; col = 1; cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); phrase = new Phrase(); } } if (col > 1) { cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); } if (row < 10) { for (int j = 0; j < 2; j++) { phrase = new Phrase(); ch = new Chunk(" ", fntb); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); row++; } } } col = 1; if (gc_bucks.size() > 0) { phrase = new Phrase(); ch = new Chunk(" Gift Certificates ", fntb); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setBorderWidth(2f); table.addCell(cell); phrase = new Phrase(); for (Buck one : gc_bucks) { ch = new Chunk("" + one.getId() + " ", fntb); phrase.add(ch); col++; if (col > 15) { row++; col = 1; cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); phrase = new Phrase(); } } if (col > 1) { cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); } if (row < 15) { for (int j = 0; j < 2; j++) { phrase = new Phrase(); ch = new Chunk(" ", fntb); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); row++; } } } if (disputes != null && disputes.size() > 0) { phrase = new Phrase(); ch = new Chunk(" Disputed Market Bucks and/or Gift Certificates (number: reason)", fntb); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setBorderWidth(2f); table.addCell(cell); row++; for (Dispute one : disputes) { phrase = new Phrase(); ch = new Chunk(one.getBuck_id() + ": " + one.getReason(), fnt); phrase.add(ch); if (one.hasNotes()) { ch = new Chunk("\nNotice: " + one.getNotes(), fnt); phrase.add(ch); row++; } cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); row++; } } if (redeem.hasNotes()) { phrase = new Phrase(); ch = new Chunk("\nNotice: " + redeem.getNotes(), fnt); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); row++; } if (row < 18) { for (int j = row; j < 18; j++) { phrase = new Phrase(); ch = new Chunk(" ", fntb); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); } } document.add(table); document.close(); writer.close(); res.setHeader("Expires", "0"); res.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); res.setHeader("Pragma", "public"); // // setting the content type res.setHeader("Content-Disposition", " attachment; filename=" + filename); res.setContentType("application/pdf"); // // the contentlength is needed for MSIE!!! res.setContentLength(baos.size()); // out = res.getOutputStream(); if (out != null) { baos.writeTo(out); } } catch (Exception ex) { System.err.println(ex); } }
From source file:ca.sqlpower.architect.profile.output.ProfilePDFFormat.java
License:Open Source License
/** * Outputs a PDF file report of the data in drs to the given * output stream.//w w w .jav a 2 s. co m * @throws SQLObjectException * @throws IllegalAccessException * @throws InstantiationException */ public void format(OutputStream out, List<ProfileResult> profileResults) throws DocumentException, IOException, SQLException, SQLObjectException, InstantiationException, IllegalAccessException, ClassNotFoundException { final int minRowsTogether = 1; // counts smaller than this are considered orphan/widow final int mtop = 50; // margin at top of page (in points) final int mbot = 50; // margin at bottom of page (page numbers are below this) // final int pbot = 20; // padding between bottom margin and bottom of body text final int mlft = 50; // margin at left side of page final int mrgt = 50; // margin at right side of page final Rectangle pagesize = PageSize.LETTER.rotate(); final Document document = new Document(pagesize, mlft, mrgt, mtop, mbot); final PdfWriter writer = PdfWriter.getInstance(document, out); final float fsize = 6f; // the font size to use in the table body final BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED); document.addTitle("Table Profiling Report"); document.addSubject("Tables: " + profileResults); document.addAuthor(System.getProperty("user.name")); document.addCreator("Power*Architect version " + ArchitectVersion.APP_FULL_VERSION); document.open(); // vertical position where next element should start // (bottom is 0; top is pagesize.height()) float pos = pagesize.height() - mtop; final PdfContentByte cb = writer.getDirectContent(); final PdfTemplate nptemplate = cb.createTemplate(50, 50); writer.setPageEvent(new PdfPageEventHelper() { // prints the "page N of <template>" footer public void onEndPage(PdfWriter writer, Document document) { int pageN = writer.getPageNumber(); String text = "Page " + pageN + " of "; float len = bf.getWidthPoint(text, fsize - 2); cb.beginText(); cb.setFontAndSize(bf, fsize - 2); cb.setTextMatrix(pagesize.width() / 2 - len / 2, mbot / 2); cb.showText(text); cb.endText(); cb.addTemplate(nptemplate, pagesize.width() / 2 - len / 2 + len, mbot / 2); } public void onCloseDocument(PdfWriter writer, Document document) { nptemplate.beginText(); nptemplate.setFontAndSize(bf, fsize - 2); nptemplate.showText(String.valueOf(writer.getPageNumber() - 1)); nptemplate.endText(); } }); document.add(new Paragraph("SQL Power Architect Profiling Report")); document.add(new Paragraph("Generated " + new java.util.Date() + " by " + System.getProperty("user.name"))); float[] widths = new float[totalColumn]; // widths of widest cells per row in pdf table LinkedList<ProfileTableStructure> profiles = new LinkedList<ProfileTableStructure>(); // 1 table per profile result Font f = new Font(bf, fsize); // This ddl generator is set to the appropriate ddl generator for the source database // every time we encounter a table profile result in the list. DDLGenerator ddlg = null; PdfPTable pdfTable = null; for (ProfileResult result : profileResults) { if (result instanceof TableProfileResult) { TableProfileResult tableResult = (TableProfileResult) result; pdfTable = new PdfPTable(widths.length); pdfTable.setWidthPercentage(100f); ProfileTableStructure oneProfile = makeNextTable(tableResult, pdfTable, bf, fsize, widths); profiles.add(oneProfile); ddlg = tableResult.getDDLGenerator(); } else if (result instanceof ColumnProfileResult) { final ColumnProfileResult columnResult = (ColumnProfileResult) result; TableProfileResult tResult = columnResult.getParent(); addBodyRow(tResult, columnResult, ddlg, pdfTable, bf, f, fsize, widths); } } double allowedTableSize = pagesize.width() - mrgt - mlft; double totalWidths = 0; for (int i = 0; i < headings.length; i++) { if (!columnsToTruncate.contains(headings[i])) { widths[i] += PIXELS_PER_BORDER; totalWidths += widths[i]; } } truncateLength = (allowedTableSize - totalWidths - (PIXELS_PER_BORDER * (columnsToTruncate.size()))) / columnsToTruncate.size(); logger.debug("Truncate length is " + truncateLength); widths = new float[totalColumn]; profiles = new LinkedList<ProfileTableStructure>(); // 1 table per profile result for (ProfileResult result : profileResults) { if (result instanceof TableProfileResult) { TableProfileResult tableResult = (TableProfileResult) result; pdfTable = new PdfPTable(widths.length); pdfTable.setWidthPercentage(100f); ProfileTableStructure oneProfile = makeNextTable(tableResult, pdfTable, bf, fsize, widths); profiles.add(oneProfile); ddlg = tableResult.getDDLGenerator(); } else if (result instanceof ColumnProfileResult) { final ColumnProfileResult columnResult = (ColumnProfileResult) result; TableProfileResult tResult = columnResult.getParent(); addBodyRow(tResult, columnResult, ddlg, pdfTable, bf, f, fsize, widths); } } for (int i = 0; i < headings.length; i++) { widths[i] += PIXELS_PER_BORDER; } // add the PdfPTables to the document; try to avoid orphan and widow rows pos = writer.getVerticalPosition(true) - fsize; logger.debug("Starting at pos=" + pos); boolean newPageInd = true; for (ProfileTableStructure profile : profiles) { pdfTable = profile.getMainTable(); pdfTable.setTotalWidth(pagesize.width() - mrgt - mlft); pdfTable.setWidths(widths); resetHeaderWidths(profile, widths); int startrow = pdfTable.getHeaderRows(); int endrow = startrow; // current page will contain header+startrow..endrow /* no other rows in the table, just the header, and the header may * contain error message */ if (endrow == pdfTable.size()) { pos = pdfTable.writeSelectedRows(0, pdfTable.getHeaderRows(), mlft, pos, cb); continue; } while (endrow < pdfTable.size()) { // figure out how many body rows fit nicely on the page float endpos = pos - calcHeaderHeight(pdfTable); // y position of page number# = (mbot/2+fsize) while ((endpos - pdfTable.getRowHeight(endrow)) >= (mbot / 2 + fsize + 2) && endrow < pdfTable.size()) { endpos -= pdfTable.getRowHeight(endrow); endrow++; } // adjust for orphan rows. Might create widows or make // endrow < startrow, which is handled later by deferring the table if (endrow < pdfTable.size() && endrow + minRowsTogether >= pdfTable.size()) { // page # maybe fall into table area, but usually that's column of // min value, usually that's enough space for both, or we should // disable page # on this page if (endrow + 1 == pdfTable.size() && endpos - pdfTable.getRowHeight(endrow) > 10) { // short by 1 row.. just squeeze it in endrow = pdfTable.size(); } else { // more than 1 row remains: shorten this page so orphans aren't lonely endrow = pdfTable.size() - minRowsTogether; } } if (endrow == pdfTable.size() || endrow - startrow >= minRowsTogether) { // this is the end of the table, or we have enough rows to bother printing pos = pdfTable.writeSelectedRows(0, pdfTable.getHeaderRows(), mlft, pos, cb); pos = pdfTable.writeSelectedRows(startrow, endrow, mlft, pos, cb); startrow = endrow; newPageInd = false; } else { // not the end of the table and not enough rows to print out if (newPageInd) throw new IllegalStateException( "PDF Page is not large engouh to display " + minRowsTogether + " row(s)"); endrow = startrow; } // new page if necessary (that is, when we aren't finished the table yet) if (endrow != pdfTable.size()) { document.newPage(); pos = pagesize.height() - mtop; newPageInd = true; } } } document.close(); }
From source file:ca.sqlpower.architect.swingui.action.ExportPlaypenToPDFAction.java
License:Open Source License
@Override public void doStuff(MonitorableImpl monitor, Map<String, Object> properties) { logger.debug("Creating PDF of playpen: " + getPlaypen()); //This is the current play pen snapshot at the time of starting the worker //thread. This way the play pen doesn't change while it is printing. PlayPen pp = playPen;//from w ww. ja v a2s.c om /* We translate the graphics to (OUTSIDE_PADDING, OUTSIDE_PADDING) * so nothing is drawn right on the edge of the document. So * we multiply by 2 so we can accomodate the translate and ensure * nothing gets drawn outside of the document size. */ final int width = pp.getBounds().width + 2 * OUTSIDE_PADDING; final int height = pp.getBounds().height + 2 * OUTSIDE_PADDING; final Rectangle ppSize = new Rectangle(width, height); OutputStream out = null; Document d = null; try { out = new BufferedOutputStream(new FileOutputStream((File) properties.get(FILE_KEY))); d = new Document(ppSize); d.addTitle(Messages.getString("ExportPlaypenToPDFAction.PdfTitle")); //$NON-NLS-1$ d.addAuthor(System.getProperty("user.name")); //$NON-NLS-1$ d.addCreator(Messages.getString("ExportPlaypenToPDFAction.powerArchitectVersion") //$NON-NLS-1$ + ArchitectVersion.APP_FULL_VERSION); PdfWriter writer = PdfWriter.getInstance(d, out); d.open(); PdfContentByte cb = writer.getDirectContent(); Graphics2D g = cb.createGraphicsShapes(width, height); // ensure a margin g.translate(OUTSIDE_PADDING, OUTSIDE_PADDING); PlayPenContentPane contentPane = pp.getContentPane(); for (int i = 0; i < contentPane.getChildren().size(); i++) { PlayPenComponent ppc = contentPane.getChildren().get(i); if (logger.isDebugEnabled()) { logger.debug("Painting component " + ppc); } g.translate(ppc.getLocation().x, ppc.getLocation().y); Font gFont = g.getFont(); ppc.paint(g); g.setFont(gFont); g.translate(-ppc.getLocation().x, -ppc.getLocation().y); monitor.setProgress(i); } pp.paintComponent(g); g.dispose(); } catch (Exception ex) { ASUtils.showExceptionDialog(getSession(), Messages.getString("ExportPlaypenToPDFAction.couldNotExportPlaypen"), //$NON-NLS-1$ ex); } finally { if (d != null) { try { d.close(); } catch (Exception ex) { ASUtils.showExceptionDialog(getSession(), Messages.getString("ExportPlaypenToPDFAction.couldNotCloseDocument"), //$NON-NLS-1$ ex); } } if (out != null) { try { out.flush(); out.close(); } catch (IOException ex) { ASUtils.showExceptionDialog(getSession(), Messages.getString("ExportPlaypenToPDFAction.couldNotClosePdfFile"), //$NON-NLS-1$ ex); } } } }
From source file:ca.sqlpower.matchmaker.swingui.action.ExportMungePenToPDFAction.java
License:Open Source License
@Override public void doStuff(MonitorableImpl monitor, Map<String, Object> properties) { if (!(session.getOldPane() instanceof MungeProcessEditor)) { JOptionPane.showMessageDialog(session.getFrame(), "We only allow PDF exports of the playpen at current.", "Cannot Export Playpen", JOptionPane.WARNING_MESSAGE); return;/*from ww w . j ava2 s . c om*/ } MungePen mungePen = ((MungeProcessEditor) session.getOldPane()).getMungePen(); /* We translate the graphics to (OUTSIDE_PADDING, OUTSIDE_PADDING) * so nothing is drawn right on the edge of the document. So * we multiply by 2 so we can accomodate the translate and ensure * nothing gets drawn outside of the document size. */ final int width = mungePen.getBounds().width + 2 * OUTSIDE_PADDING; final int height = mungePen.getBounds().height + 2 * OUTSIDE_PADDING; final Rectangle ppSize = new Rectangle(width, height); OutputStream out = null; Document d = null; try { out = new BufferedOutputStream(new FileOutputStream((File) properties.get(FILE_KEY))); d = new Document(ppSize); d.addTitle("DQguru Transform PDF Export"); d.addAuthor(System.getProperty("user.name")); d.addCreator("DQguru version " + MatchMakerVersion.APP_VERSION); PdfWriter writer = PdfWriter.getInstance(d, out); d.open(); PdfContentByte cb = writer.getDirectContent(); Graphics2D g = cb.createGraphicsShapes(width, height); // ensure a margin g.translate(OUTSIDE_PADDING, OUTSIDE_PADDING); mungePen.paintComponent(g); int j = 0; //paint each component individually to show progress for (int i = mungePen.getComponentCount() - 1; i >= 0; i--) { JComponent mpc = (JComponent) mungePen.getComponent(i); //set text and foreground as paintComponent //does not normally do this g.setColor(mpc.getForeground()); g.setFont(mpc.getFont()); logger.debug("Printing " + mpc.getName() + " to PDF"); paintComponentAndChildren(mpc, g); monitor.setProgress(j); j++; } g.dispose(); } catch (Exception ex) { SPSUtils.showExceptionDialogNoReport(session.getFrame(), "Could not export the playpen", ex); } finally { if (d != null) { try { d.close(); } catch (Exception ex) { SPSUtils.showExceptionDialogNoReport(session.getFrame(), "Could not close document for exporting playpen", ex); } } if (out != null) { try { out.flush(); out.close(); } catch (IOException ex) { SPSUtils.showExceptionDialogNoReport(session.getFrame(), "Could not close pdf file for exporting playpen", ex); } } } }
From source file:candelaria.presentacion.beans.DetalleFacturaControlador.java
public void imprimirFac() { //DateFormat dfDateFull = DateFormat.getDateInstance(DateFormat.FULL); try {/*ww w . ja v a 2 s . c o m*/ //Generamos el archivo PDF String directorioArchivos; ServletContext ctx = (ServletContext) FacesContext.getCurrentInstance().getExternalContext() .getContext(); directorioArchivos = ctx.getRealPath("/") + "reports"; String name = directorioArchivos + "/document-factura.pdf"; Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream(name)); //PdfWriter writer = PdfWriter.getInstance(document, //new FileOutputStream("C:")); Paragraph paragraph = new Paragraph(); Paragraph paragraph1 = new Paragraph(); PdfPTable table = new PdfPTable(4); PdfPTable table1 = new PdfPTable(2); PdfPTable table2 = new PdfPTable(1); PdfPTable table3 = new PdfPTable(2); PdfPTable table5 = new PdfPTable(4); PdfPTable tablaF = new PdfPTable(1); PdfPTable tablaF1 = new PdfPTable(3); PdfPTable tablaF2 = new PdfPTable(3); paragraph.add("\n\n\n"); paragraph.setAlignment(Paragraph.ALIGN_CENTER); paragraph.add("YUQUI OLGA"); paragraph.setAlignment(Paragraph.ALIGN_CENTER); paragraph.add("\n"); paragraph.add("Dir. La Candelaria Barrio Nuevo"); paragraph.setAlignment(Paragraph.ALIGN_CENTER); paragraph.add("\n"); paragraph.add("Telf: 3014019"); paragraph.setAlignment(Paragraph.ALIGN_CENTER); paragraph.add("\n"); paragraph.add("Penipe - Ecuador"); paragraph.setAlignment(Paragraph.ALIGN_CENTER); paragraph.add("\n"); paragraph.add("\n"); paragraph.setAlignment(Paragraph.ALIGN_CENTER); paragraph.add("AUTORIZACION SRI __________ - RUC.: 0600750897001"); paragraph.setAlignment(Paragraph.ALIGN_CENTER); paragraph.add("\n"); paragraph.add("FACTURA: " + facturaSel.getId_factura()); paragraph.setAlignment(Paragraph.ALIGN_CENTER); paragraph.add("\n\n\n"); paragraph.setAlignment(Paragraph.ALIGN_CENTER); paragraph1.add("\n\n"); paragraph.setAlignment(Paragraph.ALIGN_CENTER); document.open(); //primera linea PdfPCell cell5 = new PdfPCell(new Paragraph("Fecha: " + fecha_cambiada)); //PdfPCell cell6 = new PdfPCell(new Paragraph("Factura #: " + facturaSel.getId_factura())); PdfPCell cell7 = new PdfPCell(new Paragraph("Cedula: " + facturaSel.getId_cliente().getRuc_cliente())); //segunda linea PdfPCell cell8 = new PdfPCell( new Paragraph("Nombre Cliente: " + facturaSel.getId_cliente().getNombres_cliente() + facturaSel.getId_cliente().getApellidos_cliente())); //tercera fila PdfPCell cell9 = new PdfPCell( new Paragraph("Direccin: " + facturaSel.getId_cliente().getDireccion_cliente())); PdfPCell cell10 = new PdfPCell( new Paragraph("Tlefono: " + facturaSel.getId_cliente().getTelefono_cliente())); PdfPCell cellf1 = new PdfPCell(new Paragraph("SubTotal " + totalHoja)); PdfPCell cellf2 = new PdfPCell(new Paragraph("Impuesto Iva " + impuestoFactura)); PdfPCell cellf21 = new PdfPCell(new Paragraph("___________________")); PdfPCell cellf22 = new PdfPCell(new Paragraph("___________________")); PdfPCell cellf3 = new PdfPCell(new Paragraph("TOTAL " + totalFactura)); PdfPCell cellf31 = new PdfPCell(new Paragraph("FIRMA AUTORIZADA")); PdfPCell cellf32 = new PdfPCell(new Paragraph("FIRMA CLIENTE")); PdfPCell cell11 = new PdfPCell(new Paragraph("Cantidad")); PdfPCell cell12 = new PdfPCell(new Paragraph("Descripcin")); PdfPCell cell13 = new PdfPCell(new Paragraph("V. Unitario")); PdfPCell cell14 = new PdfPCell(new Paragraph("V. Total")); cell5.setHorizontalAlignment(Element.ALIGN_LEFT); //cell6.setHorizontalAlignment(Element.ALIGN_CENTER); cell7.setHorizontalAlignment(Element.ALIGN_RIGHT); cellf1.setHorizontalAlignment(Element.ALIGN_RIGHT); cellf2.setHorizontalAlignment(Element.ALIGN_RIGHT); cellf3.setHorizontalAlignment(Element.ALIGN_RIGHT); cellf21.setHorizontalAlignment(Element.ALIGN_CENTER); cellf31.setHorizontalAlignment(Element.ALIGN_CENTER); cellf22.setHorizontalAlignment(Element.ALIGN_CENTER); cellf32.setHorizontalAlignment(Element.ALIGN_CENTER); cell8.setHorizontalAlignment(Element.ALIGN_LEFT); cell9.setHorizontalAlignment(Element.ALIGN_LEFT); cell10.setHorizontalAlignment(Element.ALIGN_RIGHT); cellf21.setBorder(Rectangle.NO_BORDER); cellf31.setBorder(Rectangle.NO_BORDER); cellf22.setBorder(Rectangle.NO_BORDER); cellf32.setBorder(Rectangle.NO_BORDER); cell5.setBorder(Rectangle.NO_BORDER); //cell6.setBorder(Rectangle.NO_BORDER); cell7.setBorder(Rectangle.NO_BORDER); cell8.setBorder(Rectangle.NO_BORDER); cell9.setBorder(Rectangle.NO_BORDER); cell10.setBorder(Rectangle.NO_BORDER); //cell7.setBorder(Rectangle.NO_BORDER); //cell8.setBorder(Rectangle.NO_BORDER); cell11.setBorder(Rectangle.NO_BORDER); cell12.setBorder(Rectangle.NO_BORDER); cell13.setBorder(Rectangle.NO_BORDER); cell14.setBorder(Rectangle.NO_BORDER); cellf1.setBorder(Rectangle.NO_BORDER); cellf2.setBorder(Rectangle.NO_BORDER); cellf3.setBorder(Rectangle.NO_BORDER); cell11.setHorizontalAlignment(Element.ALIGN_LEFT); cell12.setHorizontalAlignment(Element.ALIGN_LEFT); cell13.setHorizontalAlignment(Element.ALIGN_RIGHT); cell14.setHorizontalAlignment(Element.ALIGN_RIGHT); table1.addCell(cell5); //table1.addCell(cell6); table1.addCell(cell7); //aadir segunda fila table2.addCell(cell8); //aadir tercera fila table3.addCell(cell9); table3.addCell(cell10); //aadir cuarta fila table5.addCell(cell11); table5.addCell(cell12); table5.addCell(cell13); table5.addCell(cell14); tablaF.addCell(cellf1); tablaF1.addCell(cellf21); tablaF1.addCell(cellf22); tablaF1.addCell(cellf2); tablaF2.addCell(cellf31); tablaF2.addCell(cellf32); tablaF2.addCell(cellf3); for (int x = 0; x < lstDetalleFactura.size(); x++) { PdfPCell cell1 = new PdfPCell(new Paragraph("" + lstDetalleFactura.get(x).getCantidad())); PdfPCell cell2 = new PdfPCell(new Paragraph( "" + lstDetalleFactura.get(x).getId_producto().getId_categoria().getNombre_producto())); PdfPCell cell3 = new PdfPCell(new Paragraph( "" + lstDetalleFactura.get(x).getId_producto().getId_categoria().getPrecio_producto())); PdfPCell cell4 = new PdfPCell(new Paragraph("" + lstDetalleFactura.get(x).getValor_total())); /* Chunk chunk = new Chunk( "\n" + lstDetalles.get(x).getCantidadDet() + " " + lstDetalles.get(x).getIdSer().getNombreSer() + " " + lstDetalles.get(x).getIdSer().getPrecioSer() + " " + lstDetalles.get(x).getPrecio());*/ cell1.setBorder(Rectangle.NO_BORDER); cell2.setBorder(Rectangle.NO_BORDER); cell3.setBorder(Rectangle.NO_BORDER); cell4.setBorder(Rectangle.NO_BORDER); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); cell2.setHorizontalAlignment(Element.ALIGN_LEFT); cell3.setHorizontalAlignment(Element.ALIGN_RIGHT); cell4.setHorizontalAlignment(Element.ALIGN_RIGHT); cell1.setMinimumHeight(10f); cell2.setMinimumHeight(5f); table.setTotalWidth(100f); table.addCell(cell1); table.addCell(cell2); table.addCell(cell3); table.addCell(cell4); //aadir primera fila table.setSpacingBefore(30f); table.setSpacingAfter(50f); //paragraph4.add(chunk); //paragraph4.setAlignment(Paragraph.ALIGN_JUSTIFIED_ALL); } document.add(paragraph); document.add(table1); document.add(table2); document.add(table3); document.add(paragraph1); document.add(table5); document.add(table); document.add(tablaF); document.add(tablaF1); document.add(tablaF2); //document.setFooter(event); document.close(); //---------------------------- //Abrimos el archivo PDF FacesContext context = FacesContext.getCurrentInstance(); HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse(); response.setContentType("application/pdf"); response.setHeader("Content-disposition", "inline=filename=" + name); try { response.getOutputStream().write(Util.getBytesFromFile(new File(name))); response.getOutputStream().flush(); response.getOutputStream().close(); context.responseComplete(); } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } }
From source file:ch.elexis.omnivore.data.DocHandle.java
License:Open Source License
public static List<DocHandle> assimilate(List<ImageData> images) { List<DocHandle> ret = new ArrayList<DocHandle>(); FileImportDialog fid = new FileImportDialog(Messages.DocHandle_scannedImageDialogCaption); if (fid.open() == Dialog.OK) { try {/*from ww w .java 2 s .co m*/ Document pdf = new Document(PageSize.A4); pdf.setMargins(0, 0, 0, 0); ByteArrayOutputStream baos = new ByteArrayOutputStream(100000); PdfWriter.getInstance(pdf, baos); pdf.open(); ImageLoader il = new ImageLoader(); for (int i = 0; i < images.size(); i++) { ImageData[] id = new ImageData[] { images.get(i) }; il.data = id; ByteArrayOutputStream bimg = new ByteArrayOutputStream(); il.save(bimg, SWT.IMAGE_PNG); Image image = Image.getInstance(bimg.toByteArray()); int width = id[0].width; int height = id[0].height; // 210mm = 8.27 In = 595 px bei 72dpi // 297mm = 11.69 In = 841 px if ((width > 595) || (height > 841)) { image.scaleToFit(595, 841); } pdf.add(image); } pdf.close(); DocHandle docHandle = new DocHandle(fid.category, baos.toByteArray(), ElexisEventDispatcher.getSelectedPatient(), fid.originDate, fid.title, "image.pdf", //$NON-NLS-1$ fid.keywords); ret.add(docHandle); } catch (Exception ex) { ExHandler.handle(ex); SWTHelper.showError(Messages.DocHandle_readError, Messages.DocHandle_readErrorText2); } } return ret; }
From source file:ch.emad.business.schuetu.print.PrintAgent.java
License:Apache License
public void saveFileToPrint(String name, String htmlContent) { OutputStream os = null;/*from www . j a v a 2 s .com*/ try { if (!this.init) { map.put(name, htmlContent); return; } CleanerProperties props = new CleanerProperties(); // set some properties to non-default values props.setTranslateSpecialEntities(true); props.setTransResCharsToNCR(true); props.setOmitComments(true); // do parsing LOG.info("HtmlCleaner! Body wegnehmen"); TagNode tagNode = new HtmlCleaner(props).clean(htmlContent); Object[] o = tagNode.evaluateXPath("//body"); // serialize to xml file new PrettyXmlSerializer(props).writeToFile( // --> mit utf-8 wurden sonderzeichen falsch gedruckt pathprinter+"out.xml", "utf-8" (TagNode) o[0], pathprinter + "out.xml"); String outputFile = pathprinter + name + ".pdf"; os = new FileOutputStream(outputFile); Document doc = new Document(PageSize.A4); PdfWriter.getInstance(doc, os); doc.open(); HTMLWorker hw = new HTMLWorker(doc); hw.parse(new FileReader(pathprinter + "out.xml")); doc.close(); if (this.applicationEventPublisher != null) { ch.emad.model.schuetu.model.integration.File file = new ch.emad.model.schuetu.model.integration.File(); file.setContent(IOUtils.toByteArray(new FileInputStream(new File(outputFile)))); file.setName(name + ".pdf"); OutgoingMessage fileOut = new OutgoingMessage(this); fileOut.setPayload(file); this.applicationEventPublisher.publishEvent(fileOut); } } catch (Exception e) { LOG.error(e.getMessage(), e); } finally { if (os != null) { try { os.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } FileUtils.deleteQuietly(new File(pathprinter + "out.xml")); }
From source file:ch.gpb.elexis.cst.view.CstResultPart.java
License:Open Source License
private void makeActions(final Control viewer) { actionScreenshot = new Action() { public void run() { if (profile == null) { SWTHelper.alert("No profile", "Ohne Profil kann kein Resultat erzeugt werden"); return; }//from w w w.j av a 2s .c o m GC gc = null; Image image = null; try { String latestPath = CoreHub.userCfg.get(CstPreference.CST_IDENTIFIER_LATESTPATH, null); if (latestPath == null) { latestPath = System.getProperty("user.home"); } FileDialog fd = new FileDialog(baseComposite.getShell(), SWT.SAVE); fd.setText("Save"); fd.setFilterPath(latestPath); String[] filterExt = { "*.png", "*.*" }; fd.setFilterExtensions(filterExt); fd.setFileName(CstService.generateFilename(patient)); String selected = fd.open(); if (selected == null) { return; } File selFile = new File(selected); CoreHub.userCfg.set(CstPreference.CST_IDENTIFIER_LATESTPATH, selFile.getParentFile().getAbsolutePath()); //if (profile.getAnzeigeTyp().toLowerCase().equals("effektiv")) { if (profile.getAnzeigeTyp().toLowerCase().equals(CstProfile.ANZEIGETYP_EFFEKTIV)) { if (profile.getAusgabeRichtung()) { image = new Image(viewer.getDisplay(), 1123, viewer.getBounds().height); } else { image = new Image(viewer.getDisplay(), 794, viewer.getBounds().height); } } else { image = new Image(viewer.getDisplay(), 794, viewer.getBounds().height); } ImageLoader loader = new ImageLoader(); gc = new GC(image); viewer.print(gc); gc.dispose(); loader.data = new ImageData[] { image.getImageData() }; loader.save(selected, SWT.IMAGE_PNG); } catch (Exception e) { log.error("Error saving png: " + e.toString()); showMessage("Error while saving PNG", e.getMessage()); } finally { if (image != null) { image.dispose(); } if (gc != null) { gc.dispose(); } } } }; actionScreenshot.setText(Messages.Cst_Text_Save_as_png); actionScreenshot.setToolTipText(Messages.Cst_Text_Save_as_png); actionScreenshot.setImageDescriptor( PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_OBJ_ELEMENT)); actionScreenshot.setImageDescriptor(Activator.getImageDescriptor(Activator.IMG_PNG_PATH)); // TODO: die pdf ausgabe ist eine ziemliche Baustelle - berarbeiten actionPdf = new Action() { public void run() { ////////////////////////// if (profile == null) { SWTHelper.alert("No profile", "Ohne Profil kann kein Resultat erzeugt werden"); return; } GC gc = null; Image image = null; try { String latestPath = CoreHub.userCfg.get(CstPreference.CST_IDENTIFIER_LATESTPATH, null); if (latestPath == null) { latestPath = System.getProperty("user.home"); } FileDialog fd = new FileDialog(baseComposite.getShell(), SWT.SAVE); fd.setText("Save"); fd.setFilterPath(latestPath); String[] filterExt = { "*.pdf", "*.*" }; fd.setFilterExtensions(filterExt); fd.setFileName(CstService.generateFilename(patient)); String selected = fd.open(); if (selected == null) { return; } File selFile = new File(selected); CoreHub.userCfg.set(CstPreference.CST_IDENTIFIER_LATESTPATH, selFile.getParentFile().getAbsolutePath()); int printHeigth = 1123; int printWidth = 794; if (profile.getAusgabeRichtung()) { printHeigth = 794; printWidth = 1123; } // get the image from the viewport image = new Image(viewer.getDisplay(), printWidth, viewer.getBounds().height); ImageLoader loader = new ImageLoader(); gc = new GC(image); viewer.print(gc); gc.dispose(); // prepare title data //Date date = new Date(); //SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm"); Patient patient = Patient.load(profile.getKontaktId()); //String sTitle = "Gemeinschaftspraxis Brunnmatt Dr. Beat Knzi "; String sTitle; sTitle = profile.getOutputHeader() == null ? "No header configured!" : profile.getOutputHeader(); if (sTitle == null || sTitle.length() == 0) { sTitle = "No header configured!"; } sTitle = sTitle + " Datum: " + CstService.getReadableDateAndTime(); // get option (paging to A4/ in one piece) int pdfOutputOption = 0; boolean onePage = true; PdfOptionsDialog dialog = new PdfOptionsDialog(baseComposite.getShell()); dialog.create(); if (dialog.open() == Window.OK) { pdfOutputOption = dialog.getPdfOutputOption(); if (pdfOutputOption == PdfOptionsDialog.OPTION_ONE_PAGE) { onePage = true; } else { onePage = false; } } float docHeight = viewer.getBounds().height; docHeight = docHeight / 7.5f; float fontSize = 12f; if (docHeight < 360f) { docHeight = 360f; } BufferedImage bimage = ImageUtils.convertToAWT(image.getImageData()); // create an Itextt Image from AWT BufferedImage com.lowagie.text.Image itextImage = null; java.awt.Image awtImage = null; try { awtImage = Toolkit.getDefaultToolkit().createImage(bimage.getSource()); itextImage = com.lowagie.text.Image.getInstance(awtImage, null); } catch (Exception e) { log.error("Error on image loading: " + e.toString()); e.printStackTrace(); } // only for debugging //loader.data = new ImageData[] { image.getImageData() }; //loader.save("C:\\Users\\daniel\\tmp\\debug.png", SWT.IMAGE_PNG); Rectangle pagesize = new Rectangle(595f, itextImage.getHeight() * 0.75f); // is it a4 quer? if (profile.getAusgabeRichtung()) { pagesize = new Rectangle(842f, itextImage.getHeight() * 0.75f); } //System.out.println("pagesize: " + pagesize.toString()); Document document; if (onePage) { document = new Document(pagesize); } else { document = new Document(PageSize.A4); if (profile.getAusgabeRichtung()) { document = new Document(PageSize.A4.rotate()); } } document.addCreationDate(); try { // creation of the different writers PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(selected)); // various fonts BaseFont bf_helv = BaseFont.createFont(BaseFont.HELVETICA, "Cp1252", true); BaseFont bf_times = BaseFont.createFont(BaseFont.TIMES_ROMAN, "Cp1252", true); BaseFont bf_courier = BaseFont.createFont(BaseFont.COURIER, "Cp1252", true); com.lowagie.text.Font fontHelv12 = new com.lowagie.text.Font(bf_helv, fontSize); com.lowagie.text.Font fontTimes = new com.lowagie.text.Font(bf_times, fontSize); fontTimes.setSize(fontSize); fontTimes.setStyle(com.lowagie.text.Font.ITALIC); Chunk chunkHeader = new Chunk(sTitle, FontFactory.getFont(FontFactory.HELVETICA, fontSize, com.lowagie.text.Font.NORMAL, new java.awt.Color(255, 0, 0))); com.lowagie.text.Phrase phraseHeader = new com.lowagie.text.Phrase(chunkHeader); // headers and footers must be added before the document // is opened Chunk chunkFooter = new Chunk("Seite: ", FontFactory.getFont(FontFactory.HELVETICA, fontSize, com.lowagie.text.Font.BOLD, new java.awt.Color(0, 0, 0))); Phrase phraseFooter = new Phrase(chunkFooter); phraseFooter.setFont(fontHelv12); HeaderFooter footer = new HeaderFooter(phraseFooter, true); footer.setBorder(Rectangle.NO_BORDER); footer.setAlignment(Element.ALIGN_CENTER); document.setFooter(footer); Phrase headerPhrase = new Phrase(sTitle); headerPhrase.setFont(fontTimes); HeaderFooter header = new HeaderFooter(phraseHeader, false); header.setBorder(Rectangle.BOTTOM); header.setBorderWidth(0.5f); header.setAlignment(Element.ALIGN_LEFT); document.setHeader(header); document.open(); //System.out.println("itext image w: " + itextImage.getWidth() + " h:" + itextImage.getHeight()); if (onePage) { int scale = 66; itextImage.scalePercent(scale); document.add(itextImage); } else { BufferedImage[] imageChunks = ImageUtils.splitImageByHeigth(bimage, printHeigth); for (int i = 0; i < imageChunks.length; i++) { com.lowagie.text.Image itextImage2 = com.lowagie.text.Image.getInstance( Toolkit.getDefaultToolkit().createImage(imageChunks[i].getSource()), null); // width becomes typically 523 (595 - 72) for a4Hoch or 770 (842 - 72) for A4Quer float imgWidth = document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin(); float imgHeigth = itextImage.getHeight() * 0.75f; itextImage2.setAbsolutePosition(30, 20); int scale = 66; itextImage2.scalePercent(scale); document.add(itextImage2); document.newPage(); } } // we're done! document.close(); /////////////////////////////// } catch (Exception ex) { log.error(ex.getMessage()); showMessage("Error while generating PDF", ex.getMessage()); } } finally { if (image != null) { image.dispose(); } if (gc != null) { gc.dispose(); } /* image.dispose(); gc.dispose(); */ } } }; actionPdf.setText(Messages.Cst_Text_Save_as_pdf); actionPdf.setToolTipText(Messages.Cst_Text_Save_as_pdf); /* * actionPdf.setImageDescriptor(PlatformUI.getWorkbench() .getSharedImages() * .getImageDescriptor(ISharedImages.IMG_OBJ_FILE)); */ actionPdf.setImageDescriptor(Activator.getImageDescriptor(Activator.IMG_PDF_PATH)); }
From source file:ch.gpb.elexis.kgexporter.pdf.PdfHandler.java
License:Open Source License
public static void createLaborwertTable(Patient patient, String filename, LinkedList<String[]> laborBlatt, String footerText) throws IOException, DocumentException { // step 1//w w w . ja v a 2s. c om Document document = new Document(PageSize.A4); // step 2 PdfWriter.getInstance(document, new FileOutputStream(filename)); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename)); // step 3 writer.setBoxSize("art", rect); HeaderFooterPageEvent event = new HeaderFooterPageEvent(); event.setHeaderText( patient.getVorname() + " " + patient.getName() + " (" + patient.getGeburtsdatum() + ")"); event.setFooterText(footerText); writer.setPageEvent(event); document.setMargins(56, 72, 60, 60); // step 3 document.open(); if (laborBlatt.size() == 0) { Paragraph p = new Paragraph(new Chunk("Keine Laborwerte vorhanden", fontTimesTitle)); p.setSpacingBefore(20f); document.add(p); } else { document.add(createTable2(laborBlatt)); } // step 5 document.close(); }
From source file:ch.gpb.elexis.kgexporter.pdf.PdfHandler.java
License:Open Source License
public static void createPdf(Patient patient, String filename, LinkedList<String[]> laborBlatt) throws IOException, DocumentException { BaseFont bf_helv = BaseFont.createFont(BaseFont.HELVETICA, "Cp1252", true); fontTimes = new com.lowagie.text.Font(bf_helv, 6); // step 1//from w w w . j av a 2 s .co m Document document = new Document(PageSize.A4.rotate()); // step 2 PdfWriter.getInstance(document, new FileOutputStream(filename)); // step 3 document.setHeader(getHeader( patient.getVorname() + " " + patient.getName() + " Geburtsdatum: " + patient.getGeburtsdatum())); document.open(); document.add(new Chunk("")); // << this will do the trick. // step 4 document.add(createTable2(laborBlatt)); // step 5 document.close(); }