List of usage examples for com.lowagie.text Document getPageSize
public Rectangle getPageSize()
From source file:org.drools.verifier.doc.DroolsDocsComponentFactory.java
License:Apache License
public void onEndPage(PdfWriter writer, Document document) { try {//w ww . j a va2s .c o m Image image = Image.getInstance(DroolsDocsBuilder.class.getResource("guvnor-webapp.png")); // TODO this image never existed image.setAlignment(Image.RIGHT); image.scaleAbsolute(100, 30); Rectangle page = document.getPageSize(); PdfPTable head = new PdfPTable(2); PdfPCell cell1 = new PdfPCell(image); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); cell1.setBorder(0); head.addCell(cell1); PdfPCell cell2 = new PdfPCell(new Phrase(currentDate, DroolsDocsComponentFactory.HEADER_FOOTER_TEXT)); cell2.setHorizontalAlignment(Element.ALIGN_RIGHT); cell2.setBorder(0); head.addCell(cell2); head.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin()); head.writeSelectedRows(0, -1, document.leftMargin(), page.getHeight() - document.topMargin() + head.getTotalHeight(), writer.getDirectContent()); } catch (Exception e) { throw new ExceptionConverter(e); } }
From source file:org.efaps.esjp.common.file.FileUtil_Base.java
License:Apache License
/** * Resize./*from ww w.j a va2 s . c o m*/ * * @param _parameter Parameter as passed by the eFaps API * @param _file the file * @param _fileName the file name * @param _pageSize the page size * @return the file * @throws EFapsException on error */ public File resizePdf(final Parameter _parameter, final File _file, final String _fileName, final String _pageSize) throws EFapsException { final Document document = new Document(); final File ret = getFile(_fileName, "pdf"); try { final File destFile = new File(_file.getPath() + ".tmp"); FileUtils.copyFile(_file, destFile); final OutputStream outputStream = new FileOutputStream(ret); final PdfReader pdfReader = new PdfReader(new FileInputStream(destFile)); // Create a writer for the outputstream final PdfWriter writer = PdfWriter.getInstance(document, outputStream); document.open(); PdfImportedPage page; final PdfContentByte cb = writer.getDirectContent(); int pageOfCurrentReaderPDF = 0; // Create a new page in the target for each source page. while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) { document.newPage(); pageOfCurrentReaderPDF++; page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF); document.setPageSize(page.getWidth() <= page.getHeight() ? PageSize.getRectangle(_pageSize) : PageSize.getRectangle(_pageSize).rotate()); final float widthFactor = document.getPageSize().getWidth() / page.getWidth(); final float heightFactor = document.getPageSize().getHeight() / page.getHeight(); final float factor = Math.min(widthFactor, heightFactor); final float offsetX = (document.getPageSize().getWidth() - page.getWidth() * factor) / 2; final float offsetY = (document.getPageSize().getHeight() - page.getHeight() * factor) / 2; cb.addTemplate(page, factor, 0, 0, factor, offsetX, offsetY); } pageOfCurrentReaderPDF = 0; outputStream.flush(); document.close(); outputStream.close(); } catch (final FileNotFoundException e) { LOG.error("FileNotFoundException", e); } catch (final IOException e) { LOG.error("IOException", e); } catch (final DocumentException e) { LOG.error("DocumentException", e); } return ret; }
From source file:org.goodoldai.jeff.report.pdf.PDFImageChunkBuilder.java
License:Open Source License
/** * This method transforms an image explanation chunk into a PDF report * piece and writes this piece into the provided output stream which is, in * this case, an instance of com.lowagie.text.Document. The method first * collects all general chunk data (context, rule, group, tags) and inserts * them into the report, and then retrieves the chunk content. Since the * content is, in this case, an ImageData instance, the image it relates to * (caption and URL) gets inserted into the report. If the image caption is * missing, it doesn't get inserted into the report. * * @param echunk image explanation chunk that needs to be transformed * @param stream output stream to which the transformed chunk will be * written as output (in this case com.lowagie.text.Document) * @param insertHeaders denotes if chunk headers should be inserted into the * report (true) or not (false)//from ww w .jav a 2s .c om * * @throws org.goodoldai.jeff.explanation.ExplanationException if any of the arguments are * null, if the entered chunk is not an ImageExplanationChunk instance or * if the entered output stream type is not com.lowagie.text.Document */ public void buildReportChunk(ExplanationChunk echunk, Object stream, boolean insertHeaders) { if (echunk == null) { throw new ExplanationException("The entered chunk must not be null"); } if (stream == null) { throw new ExplanationException("The entered stream must not be null"); } if (!(echunk instanceof ImageExplanationChunk)) { throw new ExplanationException("The entered chunk must be an ImageExplanationChunk instance"); } if (!(stream instanceof com.lowagie.text.Document)) { throw new ExplanationException("The entered stream must be a com.lowagie.text.Document instance"); } com.lowagie.text.Document doc = ((com.lowagie.text.Document) stream); //Insert general chunk data if (insertHeaders) PDFChunkUtility.insertChunkHeader(echunk, doc); try { //Insert content - in this case an image ImageData imdata = (ImageData) (echunk.getContent()); //Get image data Image img = Image.getInstance(getClass().getResource(imdata.getURL())); //Scale the image in order to fit the page img.scaleToFit(doc.getPageSize().getRight(doc.leftMargin() + doc.rightMargin()), doc.getPageSize().getTop(doc.topMargin() + doc.bottomMargin())); //Add image doc.add(img); //If a caption is present, insert it below the image if ((imdata.getCaption() != null) && (!imdata.getCaption().equals(""))) { doc.add(new Paragraph("IMAGE: " + imdata.getCaption())); } } catch (NullPointerException e) { throw new ExplanationException( "The image '" + ((ImageData) (echunk.getContent())).getURL() + "' could not be found"); } catch (Exception e) { throw new ExplanationException(e.getMessage()); } }
From source file:org.goodoldai.jeff.report.pdf.RTFImageChunkBuilder.java
License:Open Source License
/** * This method transforms an image explanation chunk into a PDF report * piece and writes this piece into the provided output stream which is, in * this case, an instance of com.lowagie.text.Document. The method first * collects all general chunk data (context, rule, group, tags) and inserts * them into the report, and then retrieves the chunk content. Since the * content is, in this case, an ImageData instance, the image it relates to * (caption and URL) gets inserted into the report. If the image caption is * missing, it doesn't get inserted into the report. * * @param echunk image explanation chunk that needs to be transformed * @param stream output stream to which the transformed chunk will be * written as output (in this case com.lowagie.text.Document) * @param insertHeaders denotes if chunk headers should be inserted into the * report (true) or not (false)//from w w w .j ava2 s.com * * @throws org.goodoldai.jeff.explanation.ExplanationException if any of the arguments are * null, if the entered chunk is not an ImageExplanationChunk instance or * if the entered output stream type is not com.lowagie.text.Document */ public void buildReportChunk(ExplanationChunk echunk, Object stream, boolean insertHeaders) { if (echunk == null) { throw new ExplanationException("The entered chunk must not be null"); } if (stream == null) { throw new ExplanationException("The entered stream must not be null"); } if (!(echunk instanceof ImageExplanationChunk)) { throw new ExplanationException("The entered chunk must be an ImageExplanationChunk instance"); } if (!(stream instanceof com.lowagie.text.Document)) { throw new ExplanationException("The entered stream must be a com.lowagie.text.Document instance"); } com.lowagie.text.Document doc = ((com.lowagie.text.Document) stream); //Insert general chunk data if (insertHeaders) RTFChunkUtility.insertChunkHeader(echunk, doc); try { //Insert content - in this case an image ImageData imdata = (ImageData) (echunk.getContent()); //Get image data Image img = Image.getInstance(getClass().getResource(imdata.getURL())); //Scale the image in order to fit the page img.scaleToFit(doc.getPageSize().getRight(doc.leftMargin() + doc.rightMargin()), doc.getPageSize().getTop(doc.topMargin() + doc.bottomMargin())); //Add image doc.add(img); //If a caption is present, insert it below the image if ((imdata.getCaption() != null) && (!imdata.getCaption().equals(""))) { doc.add(new Paragraph("IMAGE: " + imdata.getCaption())); } } catch (NullPointerException e) { throw new ExplanationException( "The image '" + ((ImageData) (echunk.getContent())).getURL() + "' could not be found"); } catch (Exception e) { throw new ExplanationException(e.getMessage()); } }
From source file:org.gtdfree.addons.PDFExportAddOn.java
License:Open Source License
@Override public void export(GTDModel model, ActionsCollection collection, OutputStream out, ExportAddOn.ExportOrder order, FileFilter ff, boolean compact) throws Exception { fontSelector = new FontSelector(); fontSelectorB = new FontSelector(); fontSelectorB2 = new FontSelector(); fontSelectorB4 = new FontSelector(); baseFont = fontModel.getBaseFont();// www . j ava 2 s. c o m for (BaseFont bf : fontModel.getFonts()) { fontSelector.addFont(new Font(bf, baseFontSize)); fontSelectorB.addFont(new Font(bf, baseFontSize, Font.BOLD)); fontSelectorB2.addFont(new Font(bf, baseFontSize + 2, Font.BOLD)); fontSelectorB4.addFont(new Font(bf, baseFontSize + 4, Font.BOLD)); } boolean emptyH2 = false; boolean emptyH3 = false; PdfPTable actionTable = null; Document doc = new Document(); if (sizeSet) { doc.setPageSize(pageSize); } if (marginSet) { doc.setMargins(marginLeft, marginRight, marginTop, marginBottom); } //System.out.println("PDF size "+doc.getPageSize().toString()); //System.out.println("PDF m "+marginLeft+" "+marginRight+" "+marginTop+" "+marginBottom); @SuppressWarnings("unused") PdfWriter pw = PdfWriter.getInstance(doc, out); doc.addCreationDate(); doc.addTitle("GTD-Free PDF"); doc.addSubject("GTD-Free data exported as PDF"); HeaderFooter footer = new HeaderFooter(newParagraph(), true); footer.setAlignment(HeaderFooter.ALIGN_CENTER); footer.setBorder(HeaderFooter.TOP); doc.setFooter(footer); doc.open(); Phrase ch = newTitle("GTD-Free Data"); Paragraph p = new Paragraph(ch); p.setAlignment(Paragraph.ALIGN_CENTER); PdfPTable t = new PdfPTable(1); t.setWidthPercentage(100f); PdfPCell c = newCell(p); c.setBorder(Table.BOTTOM); c.setBorderWidth(2.5f); c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); c.setPadding(5f); t.addCell(c); doc.add(t); Iterator<Object> it = collection.iterator(order); while (it.hasNext()) { Object o = it.next(); if (o == ActionsCollection.ACTIONS_WITHOUT_PROJECT) { if (order == ExportAddOn.ExportOrder.FoldersProjectsActions) { doc.add(newSubSection(ActionsCollection.ACTIONS_WITHOUT_PROJECT)); emptyH2 = false; emptyH3 = true; } else { doc.add(newSection(ActionsCollection.ACTIONS_WITHOUT_PROJECT)); emptyH2 = true; emptyH3 = false; } continue; } if (o instanceof Folder) { Folder f = (Folder) o; if (actionTable != null) { doc.add(actionTable); actionTable = null; } if (f.isProject()) { if (order == ExportAddOn.ExportOrder.ProjectsActions || order == ExportAddOn.ExportOrder.ProjectsFoldersActions) { if (emptyH2 || emptyH3) { p = newParagraph(NONE_DOT); doc.add(p); } doc.add(newSection(f.getName())); if (compact) { if (f.getDescription() != null && f.getDescription().length() > 0) { p = newParagraph(f.getDescription()); p.setIndentationLeft(10f); p.setIndentationRight(10f); doc.add(p); } } else { t = new PdfPTable(2); t.setKeepTogether(true); t.setSpacingBefore(5f); t.setWidthPercentage(66f); t.setWidths(new float[] { 0.33f, 0.66f }); c = newCell("ID"); t.addCell(c); c = newCell(newStrongParagraph(String.valueOf(f.getId()))); t.addCell(c); c = newCell("Type"); t.addCell(c); c = newCell(newStrongParagraph("Project")); t.addCell(c); c = newCell("Open"); t.addCell(c); c = newCell(newStrongParagraph(String.valueOf(f.getOpenCount()))); t.addCell(c); c = newCell("All"); t.addCell(c); c = newCell(newStrongParagraph(String.valueOf(f.size()))); t.addCell(c); c = newCell("Description"); t.addCell(c); c = newDescriptionCell(f.getDescription()); t.addCell(c); doc.add(t); } emptyH2 = true; emptyH3 = false; } else { if (emptyH3) { p = newParagraph(NONE_DOT); doc.add(p); } doc.add(newSubSection("Project:" + " " + f.getName())); emptyH2 = false; emptyH3 = true; } continue; } if (order == ExportAddOn.ExportOrder.FoldersActions || order == ExportAddOn.ExportOrder.FoldersProjectsActions) { if (emptyH2 || emptyH3) { p = newParagraph(NONE_DOT); doc.add(p); } doc.add(newSection(f.getName())); if (compact) { if (f.getDescription() != null && f.getDescription().length() > 0) { p = newParagraph(f.getDescription()); p.setIndentationLeft(10f); p.setIndentationRight(10f); doc.add(p); } } else { t = new PdfPTable(2); t.setKeepTogether(true); t.setSpacingBefore(5f); t.setWidthPercentage(66f); t.setWidths(new float[] { 0.33f, 0.66f }); c = newCell("ID"); t.addCell(c); c = newCell(newStrongParagraph(String.valueOf(f.getId()))); t.addCell(c); String type = ""; if (f.isAction()) { type = "Action list"; } else if (f.isInBucket()) { type = "In-Bucket"; } else if (f.isQueue()) { type = "Next action queue"; } else if (f.isReference()) { type = "Reference list"; } else if (f.isSomeday()) { type = "Someday/Maybe list"; } else if (f.isBuildIn()) { type = "Default list"; } c = newCell("Type"); t.addCell(c); c = newCell(newStrongParagraph(type)); t.addCell(c); c = newCell("Open"); t.addCell(c); c = newCell(newStrongParagraph(String.valueOf(f.getOpenCount()))); t.addCell(c); c = newCell("All"); t.addCell(c); c = newCell(newStrongParagraph(String.valueOf(f.size()))); t.addCell(c); c = newCell("Description"); t.addCell(c); c = newDescriptionCell(f.getDescription()); t.addCell(c); doc.add(t); } emptyH2 = true; emptyH3 = false; } else { if (emptyH3) { p = newParagraph(NONE_DOT); doc.add(p); } doc.add(newSubSection("List:" + " " + f.getName())); emptyH2 = false; emptyH3 = true; } continue; } if (o instanceof Action) { emptyH2 = false; emptyH3 = false; Action a = (Action) o; if (compact) { if (actionTable == null) { actionTable = new PdfPTable(5); actionTable.setWidthPercentage(100f); actionTable.setHeaderRows(1); actionTable.setSpacingBefore(5f); c = newHeaderCell("ID"); actionTable.addCell(c); c = newHeaderCell("Pri."); actionTable.addCell(c); c = newHeaderCell("Description"); actionTable.addCell(c); c = newHeaderCell("Reminder"); actionTable.addCell(c); c = newHeaderCell(CHECK_RESOLVED); actionTable.addCell(c); float width = doc.getPageSize().getWidth() - doc.getPageSize().getBorderWidthLeft() - doc.getPageSize().getBorderWidthRight(); int i = model.getLastActionID(); float step = baseFontSize - 1; int steps = (int) Math.floor(Math.log10(i)) + 1; // ID column float col1 = 8 + steps * step; // Priority column float col2 = 4 + 3 * (baseFontSize + 4); // Reminder column float col4 = 10 + step * 11; // Resolved column float col5 = 8 + baseFontSize; // Description column float col3 = width - col1 - col2 - col4 - col5; actionTable.setWidths(new float[] { col1, col2, col3, col4, col5 }); } addSingleActionRow(a, actionTable); } else { addSingleActionTable(model, doc, a); } } } if (actionTable != null) { doc.add(actionTable); actionTable = null; } if (emptyH2 || emptyH3) { p = newParagraph(NONE_DOT); doc.add(p); } //w.writeCharacters("Exported: "+ApplicationHelper.toISODateTimeString(new Date())); doc.close(); }
From source file:org.jbpm.designer.web.server.TransformerServlet.java
License:Apache License
public void scalePDFImage(Document document, Image image) { float scaler = ((document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin()) / image.getWidth()) * 100;/*from ww w . j av a 2s. c o m*/ image.scalePercent(scaler); }
From source file:org.jivesoftware.openfire.reporting.graph.GraphServlet.java
License:Open Source License
private void writePDFContent(HttpServletRequest request, HttpServletResponse response, JFreeChart charts[], Statistic[] stats, long starttime, long endtime, int width, int height) throws IOException { try {// w w w . java 2s .com Document document = new Document(PageSize.A4, 50, 50, 50, 50); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter writer = PdfWriter.getInstance(document, baos); writer.setPageEvent(new PDFEventListener(request)); document.open(); int index = 0; int chapIndex = 0; for (Statistic stat : stats) { String serverName = XMPPServer.getInstance().getServerInfo().getXMPPDomain(); String dateName = JiveGlobals.formatDate(new Date(starttime)) + " - " + JiveGlobals.formatDate(new Date(endtime)); Paragraph paragraph = new Paragraph(serverName, FontFactory.getFont(FontFactory.HELVETICA, 18, Font.BOLD)); document.add(paragraph); paragraph = new Paragraph(dateName, FontFactory.getFont(FontFactory.HELVETICA, 14, Font.PLAIN)); document.add(paragraph); document.add(Chunk.NEWLINE); document.add(Chunk.NEWLINE); Paragraph chapterTitle = new Paragraph(++chapIndex + ". " + stat.getName(), FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLD)); document.add(chapterTitle); // total hack: no idea what tags people are going to use in the description // possibly recommend that we only use a <p> tag? String[] paragraphs = stat.getDescription().split("<p>"); for (String s : paragraphs) { Paragraph p = new Paragraph(s); document.add(p); } document.add(Chunk.NEWLINE); PdfContentByte contentByte = writer.getDirectContent(); PdfTemplate template = contentByte.createTemplate(width, height); Graphics2D graphs2D = template.createGraphics(width, height, new DefaultFontMapper()); Rectangle2D rectangle2D = new Rectangle2D.Double(0, 0, width, height); charts[index++].draw(graphs2D, rectangle2D); graphs2D.dispose(); float x = (document.getPageSize().width() / 2) - (width / 2); contentByte.addTemplate(template, x, writer.getVerticalPosition(true) - height); document.newPage(); } 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 (DocumentException e) { Log.error("error creating PDF document: " + e.getMessage()); } }
From source file:org.kuali.kfs.module.purap.pdf.PurapPdf.java
License:Open Source License
/** * Overrides the method in PdfPageEventHelper from itext to include our watermark text to indicate that * this is a Test document and include the environment, if the environment is not a production environment. * * @param writer The PdfWriter for this document. * @param document The document.//from ww w .j ava2s.co m * @see com.lowagie.text.pdf.PdfPageEventHelper#onStartPage(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document) */ @Override public void onStartPage(PdfWriter writer, Document document) { if (!KRADUtils.isProductionEnvironment()) { PdfContentByte cb = writer.getDirectContentUnder(); cb.saveState(); cb.beginText(); cb.setFontAndSize(helv, 48); String watermarkText = "Test document (" + environment + ")"; cb.showTextAligned(Element.ALIGN_CENTER, watermarkText, document.getPageSize().width() / 2, document.getPageSize().height() / 2, 45); cb.endText(); cb.restoreState(); } if (GlobalVariables.getUserSession() != null && GlobalVariables.getUserSession().retrieveObject("isPreview") != null) { GlobalVariables.getUserSession().removeObject("isPreview"); PdfContentByte cb = writer.getDirectContentUnder(); cb.saveState(); cb.beginText(); cb.setFontAndSize(helv, 48); String watermarkText = "DRAFT"; cb.showTextAligned(Element.ALIGN_CENTER, watermarkText, document.getPageSize().width() / 2, document.getPageSize().height() / 2, 45); cb.endText(); cb.restoreState(); } }
From source file:org.kuali.kfs.module.purap.pdf.PurapPdf.java
License:Open Source License
/** * Overrides the method in PdfPageEventHelper from itext to write the headerTable, compose the footer and show the * footer.//from w ww .j a v a2 s.c o m * * @param writer The PdfWriter for this document. * @param document The document. * @see com.lowagie.text.pdf.PdfPageEventHelper#onEndPage(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document) */ @Override public void onEndPage(PdfWriter writer, Document document) { LOG.debug("onEndPage() started."); PdfContentByte cb = writer.getDirectContent(); cb.saveState(); // write the headerTable headerTable.setTotalWidth(document.right() - document.left()); headerTable.writeSelectedRows(0, -1, document.left(), document.getPageSize().height() - 10, cb); // compose the footer String text = "Page " + writer.getPageNumber() + " of "; float textSize = helv.getWidthPoint(text, 12); float textBase = document.bottom() - 20; cb.beginText(); cb.setFontAndSize(helv, 12); // show the footer float adjust = helv.getWidthPoint("0", 12); cb.setTextMatrix(document.right() - textSize - adjust, textBase); cb.showText(text); cb.endText(); cb.addTemplate(tpl, document.right() - adjust, textBase); cb.saveState(); }
From source file:org.kuali.ole.module.purap.pdf.PurapPdf.java
License:Educational Community License
/** * Overrides the method in PdfPageEventHelper from itext to include our watermark text to indicate that * this is a Test document and include the environment, if the environment is not a production environment. * * @param writer The PdfWriter for this document. * @param document The document./*w w w . j a v a 2 s .c om*/ * @see com.lowagie.text.pdf.PdfPageEventHelper#onStartPage(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document) */ public void onStartPage(PdfWriter writer, Document document) { if (!KRADUtils.isProductionEnvironment()) { PdfContentByte cb = writer.getDirectContentUnder(); cb.saveState(); cb.beginText(); cb.setFontAndSize(helv, 48); String watermarkText = "Test document (" + environment + ")"; cb.showTextAligned(Element.ALIGN_CENTER, watermarkText, document.getPageSize().width() / 2, document.getPageSize().height() / 2, 45); cb.endText(); cb.restoreState(); } if (GlobalVariables.getUserSession() != null && GlobalVariables.getUserSession().retrieveObject("isPreview") != null) { GlobalVariables.getUserSession().removeObject("isPreview"); PdfContentByte cb = writer.getDirectContentUnder(); cb.saveState(); cb.beginText(); cb.setFontAndSize(helv, 48); String watermarkText = "DRAFT"; cb.showTextAligned(Element.ALIGN_CENTER, watermarkText, document.getPageSize().width() / 2, document.getPageSize().height() / 2, 45); cb.endText(); cb.restoreState(); } }