List of usage examples for com.lowagie.text Document setPageSize
public boolean setPageSize(Rectangle pageSize)
From source file:com.songbook.pc.exporter.PdfExporter.java
License:Open Source License
private PageStats generatePDF(List<SongNode> songList, File outputFile) throws IOException, DocumentException { logger.info("Starting export to PDF file {}.", outputFile.getAbsolutePath()); // Initialize Writer Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputFile)); PageStats pageStats = new PageStats(); writer.setPageEvent(pageStats);/*w w w. j a va 2s .co m*/ // Initialize document document.setPageSize(PageSize.A4); document.setMargins(35 * POINTS_PER_MM, 10 * POINTS_PER_MM, 7 * POINTS_PER_MM, 7 * POINTS_PER_MM); document.setMarginMirroring(true); document.open(); // Add QR codes Element qrCodeSection = buildQrCodeSection(); document.add(qrCodeSection); // Line separator document.add(verseSpacing); document.add(new LineSeparator()); document.add(verseSpacing); // Build TOC Chunk tocTitle = new Chunk("SONG BOOK - TABLE OF CONTENTS", songTitleFont); tocTitle.setLocalDestination("TOC"); document.add(new Paragraph(tocTitle)); for (int i = 0; i < songList.size(); i++) { SongNode songNode = songList.get(i); int chapterNumber = i + 1; Chunk tocEntry = new Chunk(chapterNumber + ". " + songNode.getTitle(), textFont); tocEntry.setLocalGoto("SONG::" + chapterNumber); document.add(new Paragraph(tocEntry)); } document.newPage(); pageStats.setSectionLength("TOC", pageStats.getCurrentPage() - 1); // Build document for (int i = 0; i < songList.size(); i++) { // Get song node SongNode songNode = songList.get(i); // Mark song start int songStartPage = pageStats.getCurrentPage(); // Write song document.add(buildChapter(songNode, i + 1)); document.newPage(); // Record song length pageStats.setSectionLength(songNode.getTitle(), pageStats.getCurrentPage() - songStartPage); } // Close document document.close(); logger.info("COMPLETED export to PDF file {}.", outputFile.getAbsolutePath()); return pageStats; }
From source file:com.util.tools.FeraExporter.java
public void preProcessPDF(Object document) throws IOException, BadElementException, DocumentException { Document pdf = (Document) document; pdf.open();/*from w w w . j a va 2 s . c o m*/ pdf.setPageSize(PageSize.A4); ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext() .getContext(); String logo = servletContext.getRealPath("") + File.separator + "resources" + File.separator + "images" + File.separator + "Fera_Icon.png"; pdf.add(Image.getInstance(logo)); }
From source file:CPS.Core.TODOLists.PDFExporter.java
License:Open Source License
private Document prepareDocument(String filename, final String title, final String author, final String creator, final Rectangle pageSize) { System.out.println("DEBUG(PDFExporter): Creating document: " + filename); Document d = new Document(); d.setPageSize(pageSize); // TODO alter page orientation? maybe useful for seed order worksheet d.addTitle(title);//from www. j a v a 2 s . c o m d.addAuthor(author); // d.addSubject( ); // d.addKeywords( ); d.addCreator(creator); // left, right, top, bottom - scale in points (~72 points/inch) d.setMargins(35, 35, 35, 44); try { PdfWriter writer = PdfWriter.getInstance(d, new FileOutputStream(filename)); // add header and footer writer.setPageEvent(new PdfPageEventHelper() { public void onEndPage(PdfWriter writer, Document document) { try { Rectangle page = document.getPageSize(); PdfPTable head = new PdfPTable(3); head.getDefaultCell().setBorderWidth(0); head.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_LEFT); head.addCell(new Phrase(author, fontHeadFootItal)); head.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_CENTER); head.addCell(new Phrase(title, fontHeadFootReg)); head.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_RIGHT); head.addCell(""); head.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin()); head.writeSelectedRows(0, -1, document.leftMargin(), page.getHeight() - document.topMargin() + head.getTotalHeight(), writer.getDirectContent()); PdfPTable foot = new PdfPTable(3); foot.getDefaultCell().setBorderWidth(0); foot.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_LEFT); foot.addCell(new Phrase(creator, fontHeadFootItal)); foot.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_CENTER); foot.addCell(""); foot.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_RIGHT); foot.addCell(new Phrase("Page " + document.getPageNumber(), fontHeadFootReg)); foot.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin()); foot.writeSelectedRows(0, -1, document.leftMargin(), document.bottomMargin(), writer.getDirectContent()); } catch (Exception e) { throw new ExceptionConverter(e); } } }); } catch (Exception e) { e.printStackTrace(); } return d; }
From source file:daoimpl.CustomizedDocumentsView.java
public void preProcessPDF(Object document) throws IOException, BadElementException, DocumentException { Document pdf = (Document) document; pdf.open();//from w ww . j av a 2s.com pdf.setPageSize(PageSize.A4); ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext() .getContext(); String logo = servletContext.getRealPath("") + File.separator + "resources" + File.separator + "img" + File.separator + "pdf.png"; pdf.add(Image.getInstance(logo)); }
From source file:de.cuseb.bilderbuch.pdf.PdfController.java
License:Open Source License
@RequestMapping(value = "/pdf", method = RequestMethod.GET) public void generatePdf(HttpSession session, HttpServletResponse httpServletResponse) { try {/* www .ja v a 2 s . c o m*/ PdfRequest pdfRequest = (PdfRequest) session.getAttribute("pdfRequest"); httpServletResponse.setContentType("application/pdf"); Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, httpServletResponse.getOutputStream()); writer.setDefaultColorspace(PdfName.COLORSPACE, PdfName.DEFAULTRGB); //document.addAuthor(pdfRequest.getAuthor()); //document.addTitle(pdfRequest.getTitle()); document.setPageSize( new Rectangle(Utilities.millimetersToPoints(156), Utilities.millimetersToPoints(148))); document.open(); FontFactory.defaultEmbedding = true; FontFactory.register("IndieRock.ttf", "IndieRock"); Font font = FontFactory.getFont("IndieRock"); BaseFont baseFont = font.getBaseFont(); PdfContentByte cb = writer.getDirectContent(); Iterator<PdfPage> pages = pdfRequest.getPages().iterator(); while (pages.hasNext()) { PdfPage page = pages.next(); if (page.getImage() != null) { Image image = Image.getInstance(new URL(page.getImage().getUrl())); image.setDpi(300, 300); image.setAbsolutePosition(0f, 0f); image.scaleAbsolute(document.getPageSize().getWidth(), document.getPageSize().getHeight()); document.add(image); cb.saveState(); cb.beginText(); cb.setColorFill(Color.WHITE); cb.moveText(10f, 10f); cb.setFontAndSize(baseFont, 18); cb.showText(page.getSentence()); cb.endText(); cb.restoreState(); if (pages.hasNext()) { document.newPage(); } } } document.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:de.d3web.empiricaltesting.casevisualization.jung.JUNGCaseVisualizer.java
License:Open Source License
/** * Streams the graph to an OutputStream (useful for web requests!) * //from ww w .ja va 2s. c o m * @param cases List<SequentialTestCase> cases * @param outStream OutputStream */ @Override public void writeToStream(java.util.List<SequentialTestCase> cases, java.io.OutputStream outStream) throws IOException { init(cases); int w = vv.getGraphLayout().getSize().width; int h = vv.getGraphLayout().getSize().height; Document document = new Document(); try { PdfWriter writer = PdfWriter.getInstance(document, outStream); document.setPageSize(new Rectangle(w, h)); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(w, h); Graphics2D g2 = tp.createGraphics(w, h); paintGraph(g2); g2.dispose(); tp.sanityCheck(); cb.addTemplate(tp, 0, 0); cb.sanityCheck(); document.close(); } catch (DocumentException e) { throw new IOException("Error while writing to file. The file was not created. ", e); } }
From source file:de.intranda.test_ics.ImageHelper.java
License:Apache License
@SuppressWarnings("unused") private void addPage(File imageFile, PdfWriter pdfWriter, Document pdfDocument, float shrinkRatio, float rotationDegree) throws DocumentException, IOException { float pointsPerInch = 200.0f; Image pageImage = null;/*from w w w . jav a2 s.c o m*/ float pageImageHeight = 0, pageImageWidth = 0; boolean lowMemory = (shrinkRatio == 1 ? false : true); URL inputImage = imageFile.toURI().toURL(); pdfWriter.setFullCompression(); pdfWriter.setStrictImageSequence(true); pdfWriter.setLinearPageMode(); LOGGER.debug("Out of memory on loading image for pdf generation"); // ByteArrayOutputStream stream = new ByteArrayOutputStream(); BufferedImage bitmap = ImageIO.read(imageFile); // LOGGER.debug( "Size of temporary image bitmap: Width = " + bitmap.getWidth() + "; Height = " + bitmap.getHeight()); LOGGER.debug("Reading file " + imageFile.getAbsolutePath()); pageImage = Image.getInstance(bitmap, null, false); bitmap.flush(); // stream.close(); pageImage.setRotationDegrees(-rotationDegree); LOGGER.debug("Image dimensions: Width = " + pageImage.getWidth() + "; Height = " + pageImage.getHeight()); pageImageHeight = pageImage.getHeight(); pageImageWidth = pageImage.getWidth(); pageImage.setAbsolutePosition(0, 0); // Rectangle pageRect = new Rectangle(pageImageWidth/shrinkRatio, pageImageHeight/shrinkRatio); com.lowagie.text.Rectangle pageRect = new com.lowagie.text.Rectangle(pageImageWidth, pageImageHeight); LOGGER.debug("Creating rectangle: Width = " + pageRect.getWidth() + "; Height = " + pageRect.getHeight()); pdfDocument.setPageSize(pageRect); if (pdfDocument.isOpen()) { pdfDocument.newPage(); pdfWriter.getDirectContent().addImage(pageImage); } else { pdfDocument.open(); pdfWriter.getDirectContent().addImage(pageImage); } pdfWriter.flush(); System.gc(); }
From source file:de.sub.goobi.forms.ProzessverwaltungForm.java
License:Open Source License
/** * Generate result as PDF./* w w w. ja va 2 s . co m*/ */ public void generateResultAsPdf() { FacesContext facesContext = FacesContext.getCurrentInstance(); if (!facesContext.getResponseComplete()) { /* * Vorbereiten der Header-Informationen */ HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse(); try { ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext(); String contentType = servletContext.getMimeType("search.pdf"); response.setContentType(contentType); response.setHeader("Content-Disposition", "attachment;filename=\"search.pdf\""); ServletOutputStream out = response.getOutputStream(); SearchResultGeneration sr = new SearchResultGeneration(this.filter, this.showClosedProcesses, this.showArchivedProjects); HSSFWorkbook wb = sr.getResult(); List<List<HSSFCell>> rowList = new ArrayList<>(); HSSFSheet mySheet = wb.getSheetAt(0); Iterator<Row> rowIter = mySheet.rowIterator(); while (rowIter.hasNext()) { HSSFRow myRow = (HSSFRow) rowIter.next(); Iterator<Cell> cellIter = myRow.cellIterator(); List<HSSFCell> row = new ArrayList<>(); while (cellIter.hasNext()) { HSSFCell myCell = (HSSFCell) cellIter.next(); row.add(myCell); } rowList.add(row); } Document document = new Document(); Rectangle a4quer = new Rectangle(PageSize.A3.getHeight(), PageSize.A3.getWidth()); PdfWriter.getInstance(document, out); document.setPageSize(a4quer); document.open(); if (rowList.size() > 0) { Paragraph p = new Paragraph(rowList.get(0).get(0).toString()); document.add(p); PdfPTable table = new PdfPTable(9); table.setSpacingBefore(20); for (List<HSSFCell> row : rowList) { for (HSSFCell hssfCell : row) { // TODO aufhbschen und nicht toString() nutzen String stringCellValue = hssfCell.toString(); table.addCell(stringCellValue); } } document.add(table); } document.close(); out.flush(); facesContext.responseComplete(); } catch (Exception e) { logger.error(e); } } }
From source file:de.unigoettingen.sub.commons.contentlib.pdflib.PDFManager.java
License:Apache License
/****************************************************************************************************** * Adds the all pages.//from w ww.j av a2 s.com * * @param pagesizemode {@link PdfPageSize} * @param writer {@link PdfWriter} * @param pdfdoc {@link Document} * @return {@link PdfPageLabels} * * * @throws ImageInterpreterException the image interpreter exception * @throws IOException Signals that an I/O exception has occurred. * @throws MalformedURLException the malformed url exception * @throws PDFManagerException the PDF manager exception * @throws ImageManagerException *******************************************************************************************************/ private PdfPageLabels addAllPages(PdfPageSize pagesizemode, PdfWriter writer, Document pdfdoc, Watermark myWatermark) throws ImageInterpreterException, IOException, MalformedURLException, PDFManagerException, ImageManagerException { PdfPageLabels pagelabels = new PdfPageLabels(); int pageadded = 0; // sort the HashMap by the KeySet (pagenumber) Map<Integer, UrlImage> sortedMap = new TreeMap<Integer, UrlImage>(imageURLs); float scalefactor = 1; // scaling factor of the image int page_w = PaperSize.A4.width; int page_h = PaperSize.A4.height; LOGGER.debug("iterate over " + imageURLs.size() + " pages."); for (Integer imageKey : sortedMap.keySet()) { Watermark watermark = myWatermark; Image pdfImage = null; // PDF-Image LOGGER.debug("Writing page " + imageKey); boolean errorPage = false; // true if the image does not exists URL errorUrl = null; // url of the image that does not exists // ------------------------------------------------------------------------------------------------ // Title page available. Render it in pdftitlepage // ------------------------------------------------------------------------------------------------ if ((pdftitlepages != null) && (pdftitlepages.get(imageKey) != null)) { // title page PDFTitlePage pdftitlepage = pdftitlepages.get(imageKey); // create new PDF page try { pdfdoc.setPageSize(PageSize.A4); pdfdoc.setMargins(pdftitlepage.getLeftMargin(), pdftitlepage.getRightMargin(), pdftitlepage.getTopMargin(), pdftitlepage.getBottomMargin()); pageadded++; pdfdoc.newPage(); // create new page // set page name pagelabels.addPageLabel(pageadded, PdfPageLabels.EMPTY, "-"); } catch (Exception e1) { throw new PDFManagerException("PDFManagerException occured while creating new page in PDF", e1); } // render title page pdftitlepage.render(pdfdoc); } // ------------------------------------------------------------------------------------------------ // Process image with imageKey // ------------------------------------------------------------------------------------------------ UrlImage pdfpage = imageURLs.get(imageKey); if (pdfpage.getURL() != null) { boolean added = false; boolean scaled = false; URL url = pdfpage.getURL(); // pdf hack if (ContentServerConfiguration.getInstance().getUsePdf()) { LOGGER.debug("trying to find original pdf"); PdfContentByte pdfcb = null; PdfReader pdfreader = null; PdfImportedPage importpage = null; try { String pdfpath = ContentServerConfiguration.getInstance().getRepositoryPathPdf() .replace("file:///", ""); LOGGER.debug("looking in " + pdfpath + " for pdf file"); String tiffPath = ContentServerConfiguration.getInstance().getRepositoryPathImages() .replace("file:///", ""); // String urlString = url.toString(); int pageNumber = pdfpage.getPageNumber(); // UrlImage copy = new PDFPage(pdfpage); URL pdfurl = new URL(url.toString().replace(tiffPath, pdfpath) .replace(url.toString().substring(url.toString().lastIndexOf(".")), ".pdf")); LOGGER.debug("pdfurl = " + pdfurl); if (new File(pdfurl.toURI()).exists()) { LOGGER.debug("found pdf " + pdfurl.toURI()); // copy.setURL(pdfurl); pdfcb = writer.getDirectContent(); pdfreader = new PdfReader(pdfurl); importpage = writer.getImportedPage(pdfreader, pageNumber); LOGGER.debug("creating orig pdf page"); Rectangle rect = pdfreader.getPageSize(pageNumber); try { pdfdoc.setPageSize(rect); pdfdoc.newPage(); // create new page } catch (Exception e1) { throw new PDFManagerException("Exception occured while creating new page in PDF", e1); } pageadded++; pdfcb.addTemplate(importpage, 0, 0); added = true; LOGGER.debug("page:" + imageKey + " url: " + pdfurl.toString()); } } catch (URISyntaxException e) { LOGGER.debug(e); added = false; } finally { if (writer != null) { writer.freeReader(pdfreader); writer.flush(); } if (pdfreader != null) { pdfreader.close(); } } } if (!added) { // image file LOGGER.debug("using image to create pdf page"); // try to get ImageInterpreter from url ImageInterpreter myInterpreter = ImageFileFormat.getInterpreter(url, httpproxyhost, httpproxyport, httpproxyuser, httpproxypassword); try { // check preferred compression type depending on color depth Embedd preferredEmbeddingType = Embedd.ORIGBYTESTREAM; if (myInterpreter.getColordepth() == 1) { // bitonal image preferredEmbeddingType = embeddBitonalImage; } else if ((myInterpreter.getColordepth() > 1) && (myInterpreter.getSamplesperpixel() == 1)) { // greyscale image preferredEmbeddingType = embeddGreyscaleImage; } else { // color image preferredEmbeddingType = embeddColorImage; } // ------------------------------------------------------------------------------------- // Try to generate image // ------------------------------------------------------------------------------------- pdfImage = generatePdfImageFromInterpreter(myInterpreter, preferredEmbeddingType, errorPage, watermark, errorUrl); // ------------------------------------------------------------------------------------- // image couldn't be embedded yet (emergencyCase) // ------------------------------------------------------------------------------------- if (pdfImage == null) { LOGGER.warn( "Couldn't use preferred method for embedding the image. Instead had to use JPEG or RenderedImage"); // Get Interpreter and rendered Image // --------------------------------------------------------------------------------------------------------------------------------- RenderedImage ri = null; if (preferredEmbeddingType == embeddBitonalImage) { ImageManager sourcemanager = new ImageManager(url); boolean watermarkscale = ContentServerConfiguration.getInstance() .getScaleWatermark(); // should we scale // the watermark ? ri = sourcemanager.scaleImageByPixel(3000, 0, ImageManager.SCALE_BY_WIDTH, 0, null, null, watermark, watermarkscale, ImageManager.BOTTOM); myInterpreter = sourcemanager.getMyInterpreter(); } else { ri = myInterpreter.getRenderedImage(); if (watermark != null) { ri = addwatermark(ri, watermark, 2); myInterpreter.setHeight( myInterpreter.getHeight() + watermark.getRenderedImage().getHeight()); } } // scale rendered image // --------------------------------------------------------------------------------------------------------------------------------- // float scalefactorX = 1; // float scalefactorY = 1; // switch (pagesizemode) { // case ORIGINAL: // scalefactorX = 72f / myInterpreter.getXResolution(); // scalefactorY = 72f / myInterpreter.getYResolution(); // break; // default: // /* // * check, if the image needs to be scaled, because // * it's bigger than A4 calculate the new scalefactor // */ // float page_w_pixel = (float) (page_w * // myInterpreter.getXResolution() / 25.4); // float page_h_pixel = (float) (page_h * // myInterpreter.getYResolution() / 25.4); // // float res_x = myInterpreter.getXResolution(); // float res_y = myInterpreter.getYResolution(); // // long w = myInterpreter.getWidth(); // get height and // // width // long h = myInterpreter.getHeight(); // // if ((w > page_w_pixel) || (h > page_h_pixel)) { // LOGGER.debug("scale image to fit the page"); // float scalefactor_w = page_w_pixel / w; // float scalefactor_h = page_h_pixel / h; // if (scalefactor_h < scalefactor_w) { // scalefactor = scalefactor_h; // } else { // scalefactor = scalefactor_w; // } // w = (long) (w * scalefactor); // h = (long) (h * scalefactor); // } // scalefactorX = (72f / res_x) * scalefactor; // scalefactorY = (72f / res_y) * scalefactor; // break; // } // //scalefactorX = 0.2f; // //scalefactorY = 0.2f; // if (preferredEmbeddingType == embeddBitonalImage) { // ImageManager sourcemanager = new ImageManager(url); // ri = sourcemanager.scaleImageByPixel((int) // (scalefactorX*100), (int) (scalefactorY*100), // ImageManager.SCALE_BY_PERCENT, 0, null, null, // watermark, true, ImageManager.BOTTOM); // }else{ // ri = ImageManipulator.scaleInterpolationBilinear(ri, // scalefactorX, scalefactorY); // } // myInterpreter.setHeight(ri.getHeight()); // myInterpreter.setWidth(ri.getWidth()); // scaled = true; // add Watermark // --------------------------------------------------------------------------------------------------------------------------------- // ri = addwatermark(ri, watermark, // ImageManager.BOTTOM); // myInterpreter.setHeight(myInterpreter.getHeight() + // watermark.getRenderedImage().getHeight()); // Try to write into pdfImage // --------------------------------------------------------------------------------------------------------------------------------- if (myInterpreter.getColordepth() > 1) { // compress image if greyscale or color ByteArrayOutputStream bytesoutputstream = new ByteArrayOutputStream(); // JpegInterpreter jpint = new JpegInterpreter(ri); // jpint.setXResolution(myInterpreter.getXResolution()); // jpint.setYResolution(myInterpreter.getYResolution()); // jpint.writeToStream(null, bytesoutputstream); LOGGER.error("WritingJPEGImage"); writeJpegFromRenderedImageToStream(bytesoutputstream, ri, null, myInterpreter); byte[] returnbyteArray = bytesoutputstream.toByteArray(); if (bytesoutputstream != null) { bytesoutputstream.flush(); bytesoutputstream.close(); } pdfImage = Image.getInstance(returnbyteArray); returnbyteArray = null; } else { // its bitonal, but can't be embedded directly, // need to go via RenderedImage BufferedImage buffImage = ImageManipulator.fromRenderedToBuffered(ri); pdfImage = Image.getInstance(buffImage, null, false); if (myWatermark != null) { // create Image for Watermark JpegInterpreter jpint = new JpegInterpreter(myWatermark.getRenderedImage()); ByteArrayOutputStream bytesoutputstream = new ByteArrayOutputStream(); jpint.setXResolution(myInterpreter.getXResolution()); jpint.setYResolution(myInterpreter.getYResolution()); jpint.writeToStream(null, bytesoutputstream); byte[] returnbyteArray = bytesoutputstream.toByteArray(); jpint.clear(); if (bytesoutputstream != null) { bytesoutputstream.flush(); bytesoutputstream.close(); } Image blaImage = Image.getInstance(returnbyteArray); returnbyteArray = null; // set Watermark as Footer at fixed position // (200,200) Chunk c = new Chunk(blaImage, 200, 200); Phrase p = new Phrase(c); HeaderFooter hf = new HeaderFooter(p, false); pdfdoc.setFooter(hf); } // pdfdoc.setPageSize(arg0) // TODO das scheint nicht zu funktionieren... sollte // dieser Code entfernt werden? } } // end of : if (pdfImage == null) { } catch (BadElementException e) { throw new PDFManagerException("Can't create a PDFImage from a Buffered Image.", e); } catch (ImageManipulatorException e) { LOGGER.warn(e); } // --------------------------------------------------------------------------------------------------------- // place the image on the page // --------------------------------------------------------------------------------------------------------- if (pagesizemode == PdfPageSize.ORIGINAL) { // calculate the image width and height in points, create // the rectangle in points Rectangle rect = null; if (!scaled) { float image_w_points = (myInterpreter.getWidth() / myInterpreter.getXResolution()) * 72; float image_h_points = ((myInterpreter.getHeight()) / myInterpreter.getYResolution()) * 72; rect = new Rectangle(image_w_points, image_h_points); } else { rect = new Rectangle(myInterpreter.getWidth(), myInterpreter.getHeight()); } // create the pdf page according to this rectangle LOGGER.debug("creating original page sized PDF page:" + rect.getWidth() + " x " + rect.getHeight()); pdfdoc.setPageSize(rect); // create new page to put the content try { pageadded++; pdfdoc.newPage(); } catch (Exception e1) { throw new PDFManagerException( "DocumentException occured while creating page " + pageadded + " in PDF", e1); } // scale image and place it on page; scaling the image does // not scale the images bytestream if (!scaled) { pdfImage.scalePercent((72f / myInterpreter.getXResolution() * 100), (72f / myInterpreter.getYResolution() * 100)); } pdfImage.setAbsolutePosition(0, 0); // set image to lower // left corner boolean result; try { result = pdfdoc.add(pdfImage); // add it to PDF if (!result) { throw new PDFManagerException("Image \"" + url.toString() + "\" can's be added to PDF! Error during placing image on page"); } } catch (DocumentException e) { throw new PDFManagerException("DocumentException occured while adding the image to PDF", e); } } else { /* * it is not the original page size PDF will contain only A4 pages */ LOGGER.debug("creating A4 pdf page"); // create new page to put the content try { pageadded++; pdfdoc.setPageSize(PageSize.A4); pdfdoc.newPage(); // create new page } catch (Exception e1) { throw new PDFManagerException("Exception occured while creating new page in PDF", e1); } float page_w_pixel = (float) (page_w * myInterpreter.getXResolution() / 25.4); float page_h_pixel = (float) (page_h * myInterpreter.getYResolution() / 25.4); float res_x = myInterpreter.getXResolution(); float res_y = myInterpreter.getYResolution(); long w = myInterpreter.getWidth(); // get height and width long h = myInterpreter.getHeight(); /* * if the page is landscape, we have to rotate the page; this is only done in PDF, the orig image bytestream is NOT rotated */ if (w > h) { LOGGER.debug("rotate image"); // must be rotated pdfImage.setRotationDegrees(90); // change width and height long dummy = w; w = h; h = dummy; // change the resolutions x and y float dummy2 = res_x; res_x = res_y; res_y = dummy2; } /* * check, if the image needs to be scaled, because it's bigger than A4 calculate the new scalefactor */ if ((w > page_w_pixel) || (h > page_h_pixel)) { LOGGER.debug("scale image to fit the page"); float scalefactor_w = page_w_pixel / w; float scalefactor_h = page_h_pixel / h; if (scalefactor_h < scalefactor_w) { scalefactor = scalefactor_h; } else { scalefactor = scalefactor_w; } w = (long) (w * scalefactor); h = (long) (h * scalefactor); } if (!scaled) { pdfImage.scalePercent((72f / res_x * 100) * scalefactor, (72f / res_y * 100) * scalefactor); } // center the image on the page // --------------------------------------------------------------- float y_offset = 0; // y - offset // get image size in cm; height float h_cm = (float) (h / (res_x / 2.54)); // float w_cm = (float) (w / (res_y / 2.54)); // and width if ((h_cm + 2) < (page_h / 10)) { y_offset = 2 * 72f / 2.54f; } float freespace_x = ((page_w_pixel - w) / res_x * 72f); float freespace_y = ((page_h_pixel - h) / res_y * 72f) - (y_offset); // set position add image pdfImage.setAbsolutePosition(freespace_x / 2, freespace_y); boolean result; try { result = pdfdoc.add(pdfImage); } catch (DocumentException e) { LOGGER.error(e); throw new PDFManagerException("DocumentException occured while adding the image to PDF", e); } if (!result) { // placing the image in the PDF was not successful throw new PDFManagerException("Image \"" + url.toString() + "\" can's be added to PDF! Error during placing image on page"); } // draw box around the image page // ------------------------------------------------------------------------------------------------ if (pagesizemode == PdfPageSize.A4BOX) { LOGGER.debug("draw box around the image page"); // draw a black frame around the image PdfContentByte pcb = writer.getDirectContent(); // calculate upper left corner of the box (measurment is // in points) float left_x = (freespace_x / 2); float left_y = freespace_y; // calculate the lower right corner of the box // (measurement is in points) float image_w_points = (w / res_x) * 72; float image_h_points = (h / res_y) * 72; pcb.setLineWidth(1f); pcb.stroke(); pcb.rectangle(left_x, left_y, image_w_points, image_h_points); pcb.stroke(); } } // end of: if (pagesizemode == PdfPageSize.ORIGINAL) { pdfImage = null; myInterpreter.clear(); // writer.freeReader(new PdfReader(pdfpage.getURL())); } // end of : if (pdfpage.getURL() != null) { // ------------------------------------------------------------------------------------------------ // it is a page from a PDF file which should be inserted // ------------------------------------------------------------------------------------------------ else if (pdfpage.getClass() == PDFPage.class && ((PDFPage) pdfpage).getPdfreader() != null) { PdfContentByte pdfcb = writer.getDirectContent(); PdfReader pdfreader = ((PDFPage) pdfpage).getPdfreader(); PdfImportedPage importpage = writer.getImportedPage(pdfreader, pdfpage.getPageNumber()); if (pagesizemode == PdfPageSize.ORIGINAL) { LOGGER.debug("creating orig pdf page"); Rectangle rect = pdfreader.getPageSize(pdfpage.getPageNumber()); try { pdfdoc.setPageSize(rect); pdfdoc.newPage(); // create new page } catch (Exception e1) { throw new PDFManagerException("Exception occured while creating new page in PDF", e1); } // add content pageadded++; pdfcb.addTemplate(importpage, 0, 0); } else { LOGGER.debug("creating A4 pdf page"); try { pdfdoc.setPageSize(PageSize.A4); pdfdoc.newPage(); // create new page } catch (Exception e1) { throw new PDFManagerException("Exception occured while creating new page in PDF", e1); } // add content pageadded++; pdfcb.addTemplate(importpage, 0, 0); // draw box // if (pagesizemode == PdfPageSize.A4BOX) { // FIXME: nichts implementiert ? // } } } // handle pagename if (imageNames != null) { String pagename = imageNames.get(imageKey); if (pagename != null) { pagelabels.addPageLabel(pageadded, PdfPageLabels.EMPTY, pagename); } else { pagelabels.addPageLabel(pageadded, PdfPageLabels.EMPTY, "unnumbered"); } } // handle bookmarks and set destinator for bookmarks LOGGER.debug("handle bookmark(s) for page"); PdfDestination destinator = new PdfDestination(PdfDestination.FIT); setBookmarksForPage(writer, destinator, imageKey); // the key in the writer.flush(); // mashMap is the pagenumber } // end of while iterator over all pages } return pagelabels; }
From source file:dinamica.AbstractPDFOutput.java
License:LGPL
/** * Receives a byte buffer that should be filled with resulting PDF. * @param data Data module that provides recordsets to this output module * @param buf Buffer to print PDF, then used to send to browser * @throws Throwable//from ww w. ja v a 2 s .c om */ protected void createPDF(GenericTransaction data, ByteArrayOutputStream buf) throws Throwable { //pdf objects Document doc = new Document(); PdfWriter docWriter = PdfWriter.getInstance(doc, buf); //header HeaderFooter header = new HeaderFooter(new Phrase(getHeader()), false); header.setBorder(Rectangle.BOTTOM); header.setAlignment(Rectangle.ALIGN_CENTER); doc.setHeader(header); //footer HeaderFooter footer = new HeaderFooter(new Phrase(getFooter()), true); footer.setBorder(Rectangle.TOP); footer.setAlignment(Rectangle.ALIGN_RIGHT); doc.setFooter(footer); //pagesize doc.setPageSize(PageSize.LETTER); doc.open(); //title Paragraph t = new Paragraph(getReportTitle(), new Font(Font.HELVETICA, 18f)); t.setAlignment(Rectangle.ALIGN_CENTER); doc.add(t); //paragraph Paragraph p = new Paragraph("Hello World"); p.setAlignment(Rectangle.ALIGN_CENTER); doc.add(p); doc.close(); docWriter.close(); }