List of usage examples for com.lowagie.text.pdf PdfWriter getDirectContent
public PdfContentByte getDirectContent()
From source file:org.geoserver.wms.map.PDFMapResponse.java
License:Open Source License
/** * Writes the PDF.//w w w.j a v a 2 s . c om * <p> * NOTE: the document seems to actually be created in memory, and being written down to * {@code output} once we call {@link Document#close()}. If there's no other way to do so, it'd * be better to actually split out the process into produceMap/write? * </p> * * @see org.geoserver.ows.Response#write(java.lang.Object, java.io.OutputStream, * org.geoserver.platform.Operation) */ @Override public void write(Object value, OutputStream output, Operation operation) throws IOException, ServiceException { Assert.isInstanceOf(PDFMap.class, value); WMSMapContent mapContent = ((PDFMap) value).getContext(); final int width = mapContent.getMapWidth(); final int height = mapContent.getMapHeight(); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("setting up " + width + "x" + height + " image"); } try { // step 1: creation of a document-object // width of document-object is width*72 inches // height of document-object is height*72 inches com.lowagie.text.Rectangle pageSize = new com.lowagie.text.Rectangle(width, height); Document document = new Document(pageSize); document.setMargins(0, 0, 0, 0); // step 2: creation of the writer PdfWriter writer = PdfWriter.getInstance(document, output); // step 3: we open the document document.open(); // step 4: we grab the ContentByte and do some stuff with it // we create a fontMapper and read all the fonts in the font // directory DefaultFontMapper mapper = new DefaultFontMapper(); FontFactory.registerDirectories(); // we create a template and a Graphics2D object that corresponds // with it PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(width, height); PdfGraphics2D graphic = (PdfGraphics2D) tp.createGraphics(width, height, mapper); // we set graphics options if (!mapContent.isTransparent()) { graphic.setColor(mapContent.getBgColor()); graphic.fillRect(0, 0, width, height); } else { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("setting to transparent"); } int type = AlphaComposite.SRC; graphic.setComposite(AlphaComposite.getInstance(type)); Color c = new Color(mapContent.getBgColor().getRed(), mapContent.getBgColor().getGreen(), mapContent.getBgColor().getBlue(), 0); graphic.setBackground(mapContent.getBgColor()); graphic.setColor(c); graphic.fillRect(0, 0, width, height); type = AlphaComposite.SRC_OVER; graphic.setComposite(AlphaComposite.getInstance(type)); } Rectangle paintArea = new Rectangle(width, height); StreamingRenderer renderer = new StreamingRenderer(); renderer.setMapContent(mapContent); // TODO: expose the generalization distance as a param // ((StreamingRenderer) renderer).setGeneralizationDistance(0); RenderingHints hints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); renderer.setJava2DHints(hints); // we already do everything that the optimized data loading does... // if we set it to true then it does it all twice... java.util.Map rendererParams = new HashMap(); rendererParams.put("optimizedDataLoadingEnabled", new Boolean(true)); rendererParams.put("renderingBuffer", new Integer(mapContent.getBuffer())); // we need the renderer to draw everything on the batik provided graphics object rendererParams.put(StreamingRenderer.OPTIMIZE_FTS_RENDERING_KEY, Boolean.FALSE); // render everything in vector form if possible rendererParams.put(StreamingRenderer.VECTOR_RENDERING_KEY, Boolean.TRUE); if (DefaultWebMapService.isLineWidthOptimizationEnabled()) { rendererParams.put(StreamingRenderer.LINE_WIDTH_OPTIMIZATION_KEY, true); } rendererParams.put(StreamingRenderer.SCALE_COMPUTATION_METHOD_KEY, mapContent.getRendererScaleMethod()); renderer.setRendererHints(rendererParams); Envelope dataArea = mapContent.getRenderingArea(); // enforce no more than x rendering errors int maxErrors = wms.getMaxRenderingErrors(); MaxErrorEnforcer errorChecker = new MaxErrorEnforcer(renderer, maxErrors); // Add a render listener that ignores well known rendering exceptions and reports back // non // ignorable ones final RenderExceptionStrategy nonIgnorableExceptionListener; nonIgnorableExceptionListener = new RenderExceptionStrategy(renderer); renderer.addRenderListener(nonIgnorableExceptionListener); // enforce max memory usage int maxMemory = wms.getMaxRequestMemory() * KB; PDFMaxSizeEnforcer memoryChecker = new PDFMaxSizeEnforcer(renderer, graphic, maxMemory); // render the map renderer.paint(graphic, paintArea, mapContent.getRenderingArea(), mapContent.getRenderingTransform()); // render the watermark MapDecorationLayout.Block watermark = RenderedImageMapOutputFormat.getWatermark(wms.getServiceInfo()); if (watermark != null) { MapDecorationLayout layout = new MapDecorationLayout(); layout.paint(graphic, paintArea, mapContent); } // check if a non ignorable error occurred if (nonIgnorableExceptionListener.exceptionOccurred()) { Exception renderError = nonIgnorableExceptionListener.getException(); throw new ServiceException("Rendering process failed", renderError, "internalError"); } // check if too many errors occurred if (errorChecker.exceedsMaxErrors()) { throw new ServiceException("More than " + maxErrors + " rendering errors occurred, bailing out", errorChecker.getLastException(), "internalError"); } // check we did not use too much memory if (memoryChecker.exceedsMaxSize()) { long kbMax = maxMemory / KB; throw new ServiceException( "Rendering request used more memory than the maximum allowed:" + kbMax + "KB"); } graphic.dispose(); cb.addTemplate(tp, 0, 0); // step 5: we close the document document.close(); writer.flush(); writer.close(); } catch (DocumentException t) { throw new ServiceException("Error setting up the PDF", t, "internalError"); } }
From source file:org.ghost4j.document.PDFDocument.java
License:LGPL
public Document extract(int begin, int end) throws DocumentException { this.assertValidPageRange(begin, end); PDFDocument result = new PDFDocument(); ByteArrayInputStream bais = null; ByteArrayOutputStream baos = null; if (content != null) { com.lowagie.text.Document document = new com.lowagie.text.Document(); try {//from w w w . j av a2 s. co m bais = new ByteArrayInputStream(content); baos = new ByteArrayOutputStream(); PdfReader inputPDF = new PdfReader(bais); // create a writer for the outputstream PdfWriter writer = PdfWriter.getInstance(document, baos); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfImportedPage page; while (begin <= end) { document.newPage(); page = writer.getImportedPage(inputPDF, begin); cb.addTemplate(page, 0, 0); begin++; } document.close(); result.load(new ByteArrayInputStream(baos.toByteArray())); } catch (Exception e) { throw new DocumentException(e); } finally { if (document.isOpen()) document.close(); IOUtils.closeQuietly(bais); IOUtils.closeQuietly(baos); } } return result; }
From source file:org.interpss.editor.codecs.FileExportPDF.java
License:Open Source License
/** * @see java.awt.event.ActionListener#actionPerformed(ActionEvent) *//*from ww w.j a v a2 s .c o m*/ public void actionPerformed(ActionEvent e) { Document document = new Document(); try { String file = saveDialog(Translator.getString("FileSaveAsLabel") + " " + fileType.toUpperCase(), fileType.toLowerCase(), fileType.toUpperCase() + " Image"); if (file == null) return; JGraph graph = getCurrentGraph(); Object[] cells = graph.getDescendants(graph.getRoots()); if (cells.length > 0 && file != null && file.length() > 0) { PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file)); document.open(); Rectangle2D bounds = graph.getCellBounds(cells); graph.toScreen(bounds); Dimension d = bounds.getBounds().getSize(); Object[] selection = graph.getSelectionCells(); boolean gridVisible = graph.isGridVisible(); boolean doubleBuffered = graph.isDoubleBuffered(); graph.setGridVisible(false); graph.setDoubleBuffered(false); graph.clearSelection(); PdfContentByte cb = writer.getDirectContent(); cb.saveState(); cb.concatCTM(1, 0, 0, 1, 50, 400); Graphics2D g2 = cb.createGraphics(d.width + 10, d.height + 10); g2.setColor(graph.getBackground()); g2.fillRect(0, 0, d.width + 10, d.height + 10); g2.translate(-bounds.getX() + 5, -bounds.getY() + 5); graph.paint(g2); graph.setSelectionCells(selection); graph.setGridVisible(gridVisible); graph.setDoubleBuffered(doubleBuffered); g2.dispose(); cb.restoreState(); } } catch (IOException ex) { graphpad.error(ex.getMessage()); } catch (DocumentException e2) { graphpad.error(e2.getMessage()); } document.close(); }
From source file:org.jaffa.modules.printing.services.PdfHelper.java
License:Open Source License
/** * Scale the pages of the input pdfOutput document to the given pageSize. * @param pdfOutput The PDF document to rescale, in the form of a ByteArrayOutputStream. * @param pageSize The new page size to which to scale to PDF document, e.g. "A4". * @param noEnlarge If true, center pages instead of enlarging them. * Use noEnlarge if the new page size is larger than the old one * and the pages should be centered instead of enlarged. * @param preserveAspectRatio If true, the aspect ratio will be preserved. * @return The PDF document with its pages scaled to the input pageSize. *///from w ww.j a v a 2 s . c o m public static byte[] scalePdfPages(byte[] pdfOutput, String pageSize, boolean noEnlarge, boolean preserveAspectRatio) throws FormPrintException { if (pageSize == null || pdfOutput == null) { return pdfOutput; } // Get the dimensions of the given pageSize in PostScript points. // A PostScript point is a 72th of an inch. float dimX; float dimY; Rectangle rectangle; try { rectangle = PageSize.getRectangle(pageSize); } catch (Exception ex) { FormPrintException e = new PdfProcessingException( "scalePdfPages - Invalid page size = " + pageSize + " "); log.error(" scalePdfPages - Invalid page size: " + pageSize + ". " + ex.getMessage() + ". "); throw e; } if (rectangle != null) { dimX = rectangle.getWidth(); dimY = rectangle.getHeight(); } else { FormPrintException e = new PdfProcessingException("scalePdfPages - Invalid page size: " + pageSize); log.error(" scalePdfPages - Invalid page size: " + pageSize); throw e; } //Create portrait and landscape rectangles for the given page size. Rectangle portraitPageSize; Rectangle landscapePageSize; if (dimY > dimX) { portraitPageSize = new Rectangle(dimX, dimY); landscapePageSize = new Rectangle(dimY, dimX); } else { portraitPageSize = new Rectangle(dimY, dimX); landscapePageSize = new Rectangle(dimX, dimY); } // Remove the document rotation before resizing the document. byte[] output = removeRotation(pdfOutput); PdfReader currentReader = null; try { currentReader = new PdfReader(output); } catch (IOException ex) { FormPrintException e = new PdfProcessingException("scalePdfPages - Failed to create a PDF Reader"); log.error(" scalePdfPages - Failed to create a PDF Reader "); throw e; } OutputStream baos = new ByteArrayOutputStream(); Rectangle newSize = new Rectangle(dimX, dimY); Document document = new Document(newSize, 0, 0, 0, 0); PdfWriter writer = null; try { writer = PdfWriter.getInstance(document, baos); } catch (DocumentException ex) { FormPrintException e = new PdfProcessingException("scalePdfPages - Failed to create a PDF Writer"); log.error(" scalePdfPages - Failed to create a PDF Writer "); throw e; } document.open(); PdfContentByte cb = writer.getDirectContent(); PdfImportedPage page; float offsetX, offsetY; for (int i = 1; i <= currentReader.getNumberOfPages(); i++) { Rectangle currentSize = currentReader.getPageSizeWithRotation(i); if (currentReader.getPageRotation(i) != 0) { FormPrintException e = new PdfProcessingException("Page Rotation, " + currentReader.getPageRotation(i) + ", must be removed to re-scale the form."); log.error(" Page Rotation, " + currentReader.getPageRotation(i) + ", must be removed to re-scale the form. "); throw e; } //Reset the page size for each page because there may be a mix of sizes in the document. float currentWidth = currentSize.getWidth(); float currentHeight = currentSize.getHeight(); if (currentWidth > currentHeight) { newSize = landscapePageSize; } else { newSize = portraitPageSize; } document.setPageSize(newSize); document.newPage(); float factorX = newSize.getWidth() / currentSize.getWidth(); float factorY = newSize.getHeight() / currentSize.getHeight(); // Use noEnlarge if the new page size is larger than the old one // and the pages should be centered instead of enlarged. if (noEnlarge) { if (factorX > 1) { factorX = 1; } if (factorY > 1) { factorY = 1; } } if (preserveAspectRatio) { factorX = Math.min(factorX, factorY); factorY = factorX; } offsetX = (newSize.getWidth() - (currentSize.getWidth() * factorX)) / 2f; offsetY = (newSize.getHeight() - (currentSize.getHeight() * factorY)) / 2f; page = writer.getImportedPage(currentReader, i); cb.addTemplate(page, factorX, 0, 0, factorY, offsetX, offsetY); } document.close(); return ((ByteArrayOutputStream) baos).toByteArray(); }
From source file:org.jaffa.modules.printing.services.PdfHelper.java
License:Open Source License
/** * Remove the rotation from the pdfOutput document pages. *///w w w. j a v a2 s . c om private static byte[] removeRotation(byte[] pdfOutput) throws FormPrintException { PdfReader currentReader = null; try { currentReader = new PdfReader(pdfOutput); } catch (IOException ex) { FormPrintException e = new PdfProcessingException( "Remove PDF Page Rotation - Failed to create a PDF Reader"); log.error(" Remove PDF Page Rotation - Failed to create a PDF Reader "); throw e; } boolean needed = false; for (int i = 1; i <= currentReader.getNumberOfPages(); i++) { if (currentReader.getPageRotation(i) != 0) { needed = true; } } if (!needed) { return pdfOutput; } OutputStream baos = new ByteArrayOutputStream(); Document document = new Document(); PdfWriter writer = null; try { writer = PdfWriter.getInstance(document, baos); } catch (DocumentException ex) { FormPrintException e = new PdfProcessingException( "Remove PDF Page Rotation - Failed to create a PDF Writer"); log.error(" Remove PDF Page Rotation - Failed to create a PDF Writer "); throw e; } PdfContentByte cb = null; PdfImportedPage page; for (int i = 1; i <= currentReader.getNumberOfPages(); i++) { Rectangle currentSize = currentReader.getPageSizeWithRotation(i); currentSize = new Rectangle(currentSize.getWidth(), currentSize.getHeight()); // strip rotation document.setPageSize(currentSize); if (cb == null) { document.open(); cb = writer.getDirectContent(); } else { document.newPage(); } int rotation = currentReader.getPageRotation(i); page = writer.getImportedPage(currentReader, i); float a, b, c, d, e, f; if (rotation == 0) { a = 1; b = 0; c = 0; d = 1; e = 0; f = 0; } else if (rotation == 90) { a = 0; b = -1; c = 1; d = 0; e = 0; f = currentSize.getHeight(); } else if (rotation == 180) { a = -1; b = 0; c = 0; d = -1; e = currentSize.getWidth(); f = currentSize.getHeight(); } else if (rotation == 270) { a = 0; b = 1; c = -1; d = 0; e = currentSize.getWidth(); f = 0; } else { FormPrintException ex = new PdfProcessingException( "Remove PDF Page Rotation - Unparsable rotation value: " + rotation); log.error(" Remove PDF Page Rotation - Unparsable form rotation value: " + rotation); throw ex; } cb.addTemplate(page, a, b, c, d, e, f); } document.close(); return ((ByteArrayOutputStream) baos).toByteArray(); }
From source file:org.jdesktop.swingx.jxmlnote.report.pdf.PdfReport.java
License:Open Source License
public void beginReport(File output) throws ReportException { try {//w w w. ja v a2 s.c o m _canceled = false; _doc = new Document(); _writer = PdfWriter.getInstance(_doc, new FileOutputStream(output)); setPageSize(PageSize.A4); setMargins(new Rectangle(72.0f, 72.0f, 72.0f, 72.0f)); _writer.setPageEvent(new PdfPageEvent() { public void onChapter(PdfWriter arg0, Document arg1, float arg2, com.lowagie.text.Paragraph arg3) { } public void onChapterEnd(PdfWriter arg0, Document arg1, float arg2) { } public void onCloseDocument(PdfWriter arg0, Document arg1) { PdfReport.super.getReportListeners().informEndReport(PdfReport.this); } public void onGenericTag(PdfWriter arg0, Document arg1, com.lowagie.text.Rectangle arg2, String arg3) { } public void onOpenDocument(PdfWriter arg0, Document arg1) { } public void onParagraph(PdfWriter arg0, Document arg1, float arg2) { } public void onParagraphEnd(PdfWriter arg0, Document arg1, float arg2) { } public void onSection(PdfWriter arg0, Document arg1, float arg2, int arg3, com.lowagie.text.Paragraph arg4) { } public void onSectionEnd(PdfWriter arg0, Document arg1, float arg2) { } public void onStartPage(PdfWriter wrt, Document doc) { } public void onEndPage(PdfWriter wrt, Document doc) { try { ReportListeners _listeners = PdfReport.super.getReportListeners(); _listeners.informNextPage(PdfReport.this); Vector<ReportElement> vhdr = _listeners.getHeader(PdfReport.this); Vector<ReportElement> vftr = _listeners.getFooter(PdfReport.this); PdfContentByte cb = wrt.getDirectContent(); // write headers on top of each other if (vhdr != null) { Iterator<ReportElement> it = vhdr.iterator(); while (it.hasNext()) { ReportElement hdr = it.next(); Rectangle pageSize = PdfReport.this.getPageRect(); Rectangle margins = PdfReport.this.getMargins(); float ytop = pageSize.top() - margins.top(); float hdrHeight = PdfReport.this.getHeight(hdr, null); float rpos = (margins.top() - hdrHeight) / 2; float hytop = ytop + rpos + hdrHeight; if (hdr instanceof PdfTable) { int firstRow = 0, lastRow = -1; PdfTable phdr = (PdfTable) hdr; phdr.writeSelectedRows(firstRow, lastRow, margins.left(), hytop, cb); } else if (hdr instanceof PdfParagraph) { PdfParagraph ppar = (PdfParagraph) hdr; ColumnText ct = new ColumnText(cb); float textWidth = PdfReport.this.getTextWidth(); ct.addElement(ppar); ct.setSimpleColumn(margins.left(), ytop + rpos, margins.left() + textWidth, hytop); ct.go(); } } } // write footers on top of each other if (vftr != null) { Iterator<ReportElement> it = vftr.iterator(); while (it.hasNext()) { ReportElement ftr = it.next(); Rectangle margins = PdfReport.this.getMargins(); float ytop = margins.bottom(); float hdrHeight = PdfReport.this.getHeight(ftr, null); float rpos = (margins.bottom() - hdrHeight) / 2; float hytop = ytop - rpos; if (ftr instanceof PdfTable) { int firstRow = 0, lastRow = -1; PdfTable pftr = (PdfTable) ftr; pftr.writeSelectedRows(firstRow, lastRow, margins.left(), hytop, cb); } else if (ftr instanceof PdfParagraph) { PdfParagraph ppar = (PdfParagraph) ftr; ColumnText ct = new ColumnText(cb); float textWidth = PdfReport.this.getTextWidth(); ct.addElement(ppar); ct.setSimpleColumn(margins.left(), rpos, margins.left() + textWidth, hytop); ct.go(); } } } } catch (ReportException e) { DefaultXMLNoteErrorHandler.exception(e); } catch (DocumentException e) { DefaultXMLNoteErrorHandler.exception(e); } } }); } catch (Exception e) { throw new ReportException(e); } }
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 {/*from w w w. j a v a 2s. c o m*/ 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.jpedal.examples.simpleviewer.utils.ItextFunctions.java
License:Open Source License
public void nup(int pageCount, PdfPageData currentPageData, ExtractPDFPagesNup extractPage) { try {// w w w. ja v a2 s .c om int[] pgsToEdit = extractPage.getPages(); if (pgsToEdit == null) return; //get user choice final String output_dir = extractPage.getRootDir() + separator + fileName + separator + "PDFs" + separator; File testDirExists = new File(output_dir); if (!testDirExists.exists()) testDirExists.mkdirs(); List pagesToEdit = new ArrayList(); for (int i = 0; i < pgsToEdit.length; i++) pagesToEdit.add(new Integer(pgsToEdit[i])); PdfReader reader = new PdfReader(selectedFile); File fileToSave = new File(output_dir + "export_" + fileName + ".pdf"); if (fileToSave.exists()) { int n = currentGUI.showOverwriteDialog(fileToSave.getAbsolutePath(), false); if (n == 0) { // clicked yes so just carry on } else { // clicked no, so exit return; } } int rows = extractPage.getLayoutRows(); int coloumns = extractPage.getLayoutColumns(); int paperWidth = extractPage.getPaperWidth(); int paperHeight = extractPage.getPaperHeight(); Rectangle pageSize = new Rectangle(paperWidth, paperHeight); String orientation = extractPage.getPaperOrientation(); Rectangle newSize = null; if (orientation.equals(Messages.getMessage("PdfViewerNUPOption.Auto"))) { if (coloumns > rows) newSize = new Rectangle(pageSize.height(), pageSize.width()); else newSize = new Rectangle(pageSize.width(), pageSize.height()); } else if (orientation.equals("Portrait")) { newSize = new Rectangle(pageSize.width(), pageSize.height()); } else if (orientation.equals("Landscape")) { newSize = new Rectangle(pageSize.height(), pageSize.width()); } String scale = extractPage.getScale(); float leftRightMargin = extractPage.getLeftRightMargin(); float topBottomMargin = extractPage.getTopBottomMargin(); float horizontalSpacing = extractPage.getHorizontalSpacing(); float verticalSpacing = extractPage.getVerticalSpacing(); Rectangle unitSize = null; if (scale.equals("Auto")) { float totalHorizontalSpacing = (coloumns - 1) * horizontalSpacing; int totalWidth = (int) (newSize.width() - leftRightMargin * 2 - totalHorizontalSpacing); int unitWidth = totalWidth / coloumns; float totalVerticalSpacing = (rows - 1) * verticalSpacing; int totalHeight = (int) (newSize.height() - topBottomMargin * 2 - totalVerticalSpacing); int unitHeight = totalHeight / rows; unitSize = new Rectangle(unitWidth, unitHeight); } else if (scale.equals("Use Original Size")) { unitSize = null; } else if (scale.equals("Specified")) { unitSize = new Rectangle(extractPage.getScaleWidth(), extractPage.getScaleHeight()); } int order = extractPage.getPageOrdering(); int pagesPerPage = rows * coloumns; int repeats = 1; if (extractPage.getRepeat() == REPEAT_AUTO) repeats = coloumns * rows; else if (extractPage.getRepeat() == REPEAT_SPECIFIED) repeats = extractPage.getCopies(); Document document = new Document(newSize, 0, 0, 0, 0); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileToSave)); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfImportedPage importedPage; float offsetX = 0, offsetY = 0, factor; int actualPage = 0, page = 0; Rectangle currentSize; boolean isProportional = extractPage.isScaleProportional(); for (int i = 1; i <= pageCount; i++) { if (pagesToEdit.contains(new Integer(i))) { for (int j = 0; j < repeats; j++) { int currentUnit = page % pagesPerPage; if (currentUnit == 0) { document.newPage(); actualPage++; } currentSize = reader.getPageSizeWithRotation(i); if (unitSize == null) unitSize = currentSize; int currentColoumn = 0, currentRow = 0; if (order == ORDER_DOWN) { currentColoumn = currentUnit / rows; currentRow = currentUnit % rows; offsetX = unitSize.width() * currentColoumn; offsetY = newSize.height() - (unitSize.height() * (currentRow + 1)); } else if (order == ORDER_ACCROS) { currentColoumn = currentUnit % coloumns; currentRow = currentUnit / coloumns; offsetX = unitSize.width() * currentColoumn; offsetY = newSize.height() - (unitSize.height() * ((currentUnit / coloumns) + 1)); } factor = Math.min(unitSize.width() / currentSize.width(), unitSize.height() / currentSize.height()); float widthFactor = factor, heightFactor = factor; if (!isProportional) { widthFactor = unitSize.width() / currentSize.width(); heightFactor = unitSize.height() / currentSize.height(); } else { offsetX += ((unitSize.width() - (currentSize.width() * factor)) / 2f); offsetY += ((unitSize.height() - (currentSize.height() * factor)) / 2f); } offsetX += (horizontalSpacing * currentColoumn) + leftRightMargin; offsetY -= ((verticalSpacing * currentRow) + topBottomMargin); importedPage = writer.getImportedPage(reader, i); double rotation = currentSize.getRotation() * Math.PI / 180; /** * see * http://itextdocs.lowagie.com/tutorial/directcontent/coordinates/index.html * for information about transformation matrices, and the coordinate system */ int mediaBoxX = -currentPageData.getMediaBoxX(i); int mediaBoxY = -currentPageData.getMediaBoxY(i); float a, b, c, d, e, f; switch (currentSize.getRotation()) { case 0: a = widthFactor; b = 0; c = 0; d = heightFactor; e = offsetX + (mediaBoxX * widthFactor); f = offsetY + (mediaBoxY * heightFactor); cb.addTemplate(importedPage, a, b, c, d, e, f); break; case 90: a = 0; b = (float) (Math.sin(rotation) * -heightFactor); c = (float) (Math.sin(rotation) * widthFactor); d = 0; e = offsetX + (mediaBoxY * widthFactor); f = ((currentSize.height() * heightFactor) + offsetY) - (mediaBoxX * heightFactor); cb.addTemplate(importedPage, a, b, c, d, e, f); break; case 180: a = (float) (Math.cos(rotation) * widthFactor); b = 0; c = 0; d = (float) (Math.cos(rotation) * heightFactor); e = (offsetX + (currentSize.width() * widthFactor)) - (mediaBoxX * widthFactor); f = ((currentSize.height() * heightFactor) + offsetY) - (mediaBoxY * heightFactor); cb.addTemplate(importedPage, a, b, c, d, e, f); break; case 270: a = 0; b = (float) (Math.sin(rotation) * -heightFactor); c = (float) (Math.sin(rotation) * widthFactor); d = 0; e = (offsetX + (currentSize.width() * widthFactor)) - (mediaBoxY * widthFactor); f = offsetY + (mediaBoxX * heightFactor); cb.addTemplate(importedPage, a, b, c, d, e, f); break; } page++; } } } document.close(); currentGUI.showMessageDialog( Messages.getMessage("PdfViewerMessage.PagesSavedAsPdfTo") + " " + output_dir); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.jpedal.examples.simpleviewer.utils.ItextFunctions.java
License:Open Source License
public void handouts(String file) { try {//from w ww . j a va 2s. c o m File src = new File(selectedFile); File dest = new File(file); int pages = 4; float x1 = 30f; float x2 = 280f; float x3 = 320f; float x4 = 565f; float[] y1 = new float[pages]; float[] y2 = new float[pages]; float height = (778f - (20f * (pages - 1))) / pages; y1[0] = 812f; y2[0] = 812f - height; for (int i = 1; i < pages; i++) { y1[i] = y2[i - 1] - 20f; y2[i] = y1[i] - height; } // we create a reader for a certain document PdfReader reader = new PdfReader(src.getAbsolutePath()); // we retrieve the total number of pages int n = reader.getNumberOfPages(); // step 1: creation of a document-object Document document = new Document(PageSize.A4); // step 2: we create a writer that listens to the document PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest)); // step 3: we open the document document.open(); PdfContentByte cb = writer.getDirectContent(); PdfImportedPage page; int rotation; int i = 0; int p = 0; // step 4: we add content while (i < n) { i++; Rectangle rect = reader.getPageSizeWithRotation(i); float factorx = (x2 - x1) / rect.width(); float factory = (y1[p] - y2[p]) / rect.height(); float factor = (factorx < factory ? factorx : factory); float dx = (factorx == factor ? 0f : ((x2 - x1) - rect.width() * factor) / 2f); float dy = (factory == factor ? 0f : ((y1[p] - y2[p]) - rect.height() * factor) / 2f); page = writer.getImportedPage(reader, i); rotation = reader.getPageRotation(i); if (rotation == 90 || rotation == 270) { cb.addTemplate(page, 0, -factor, factor, 0, x1 + dx, y2[p] + dy + rect.height() * factor); } else { cb.addTemplate(page, factor, 0, 0, factor, x1 + dx, y2[p] + dy); } cb.setRGBColorStroke(0xC0, 0xC0, 0xC0); cb.rectangle(x3 - 5f, y2[p] - 5f, x4 - x3 + 10f, y1[p] - y2[p] + 10f); for (float l = y1[p] - 19; l > y2[p]; l -= 16) { cb.moveTo(x3, l); cb.lineTo(x4, l); } cb.rectangle(x1 + dx, y2[p] + dy, rect.width() * factor, rect.height() * factor); cb.stroke(); p++; if (p == pages) { p = 0; document.newPage(); } } // step 5: we close the document document.close(); } catch (Exception e) { System.err.println(e.getMessage()); } }
From source file:org.jplot2d.renderer.PdfExporter.java
License:Open Source License
@Override public void render(ComponentEx comp, List<CacheableBlock> cacheBlockList) { Dimension size = getDeviceBounds(comp).getSize(); Document document = new Document(new Rectangle(size.width, size.height), 0, 0, 0, 0); PdfWriter writer; try {//from w w w . j a v a2s . com writer = PdfWriter.getInstance(document, os); } catch (DocumentException e) { /* * should not happen but if it happens it should be notified to the integration instead of leaving it * half-done and tell nothing. */ throw new RuntimeException("Error creating PDF document", e); } document.open(); if (title != null) { document.addTitle(title); } PdfContentByte cb = writer.getDirectContent(); Graphics2D g = cb.createGraphics(size.width, size.height); for (CacheableBlock cblock : cacheBlockList) { List<ComponentEx> sublist = cblock.getSubcomps(); for (ComponentEx subcomp : sublist) { subcomp.draw(g); } } g.dispose(); document.close(); }