List of usage examples for com.lowagie.text Rectangle Rectangle
public Rectangle(float urx, float ury)
Rectangle
-object starting from the origin (0, 0). 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 {/* w w w . jav a 2s. 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 www .j a va 2 s . 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.dfki.owlsmx.gui.util.Converter.java
License:Open Source License
public static void convertToPdf(JFreeChart chart, int width, int height, String filename) { // step 1 Document document = new Document(new Rectangle(width, height)); try {//from w w w .j a v a 2s . c o m // step 2 PdfWriter writer; writer = PdfWriter.getInstance(document, new FileOutputStream(filename)); // step 3 document.open(); // step 4 PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(width, height); Graphics2D g2d = tp.createGraphics(width, height, new DefaultFontMapper()); Rectangle2D r2d = new Rectangle2D.Double(0, 0, width, height); chart.draw(g2d, r2d); g2d.dispose(); cb.addTemplate(tp, 0, 0); } catch (DocumentException de) { } catch (FileNotFoundException e) { } // step 5 document.close(); }
From source file:de.sub.goobi.forms.ProzessverwaltungForm.java
License:Open Source License
/** * Generate result as PDF./*from ww w . ja v a 2 s . c om*/ */ 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./* w w w. j a va 2 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:de.unigoettingen.sub.commons.contentlib.pdflib.PDFManager.java
License:Apache License
/** * Sets the default size of the page and creates the pdf document (com.lowagie.text.Document) instance. * /* www .j av a 2 s. c o m*/ * @param pagesizemode the pagesizemode * @param pagesize the pagesize * * @return the pdf-document instance * * @throws ImageInterpreterException the image interpreter exception * @throws IOException Signals that an I/O exception has occurred. */ private Document setPDFPageSizeForFirstPage(PdfPageSize pagesizemode, Rectangle pagesize) throws ImageInterpreterException, IOException { Document pdfdoc; boolean isTitlePage = false; // set page size of the PDF if ((pagesizemode == PdfPageSize.ORIGINAL) && (pdftitlepage == null)) { LOGGER.debug("Page size of the first page is size of first image"); // GDZ: Check if this changes the order of the Pages // What if 0000002 ist intentionaly before 00000001 ? // page size is set to size of first page of the document // (first image of imageURLs) Map<Integer, UrlImage> sortedMap = new TreeMap<Integer, UrlImage>(imageURLs); for (Integer key : sortedMap.keySet()) { // do the image exists ? while (key < sortedMap.size() && sortedMap.get(key).getURL().openConnection().getContentLength() == 0) { key++; } if ((pdftitlepages != null) && (pdftitlepages.get(key) != null)) { // title page for Document Part available; set pagesize to // A4 pagesize = setA4pagesize(); isTitlePage = true; break; } // no title page, so get the size of the first page UrlImage pdfpage = imageURLs.get(key); if (pdfpage.getURL() != null) { // it's an image file URL url = pdfpage.getURL(); LOGGER.debug("Using image" + pdfpage.getURL().toString()); ImageInterpreter myInterpreter = ImageFileFormat.getInterpreter(url, httpproxyhost, httpproxyport, httpproxyuser, httpproxypassword); float xres = myInterpreter.getXResolution(); float yres = myInterpreter.getYResolution(); int height = myInterpreter.getHeight(); int width = myInterpreter.getWidth(); int image_w_points = (width * 72) / ((int) xres); int image_h_points = (height * 72) / ((int) yres); pagesize = new Rectangle(image_w_points, image_h_points); // set // a retangle in the size of the image break; // get out of loop } else if (pdfpage.getClass() == PDFPage.class && ((PDFPage) pdfpage).getPdfreader() != null) { // a pdf page, not an image file PdfReader pdfreader = ((PDFPage) pdfpage).getPdfreader(); pagesize = pdfreader.getPageSize(pdfpage.getPageNumber()); } } } else if (pdftitlepage != null) { isTitlePage = true; LOGGER.debug("Page size of the first page is A4, cause it is a title page"); pagesize = setA4pagesize(); } else { // page size is set to A4, because either the whole // PDF is in A4 or we will have a title page which is // in A4 LOGGER.debug("Page size of the first page is A4, page size mode is " + pagesizemode); pagesize = setA4pagesize(); } if (pagesize != null) { // pagesize is a rectangle; pagesize sets the // page for the first page pdfdoc = new Document(pagesize, 2.5f * 72f / 2.54f, 2.5f * 72f / 2.54f, 2.5f * 72f / 2.54f, 3f * 72f / 2.54f); if (isTitlePage) { pdfdoc.setMargins(pdftitlepage.getLeftMargin(), pdftitlepage.getRightMargin(), pdftitlepage.getTopMargin(), pdftitlepage.getBottomMargin()); } } else { LOGGER.warn("No pagesize available.... strange!"); pdfdoc = new Document(); } return pdfdoc; }
From source file:de.unigoettingen.sub.commons.contentlib.pdflib.PDFManager.java
License:Apache License
/** * ************************************************************************* create a {@link Rectangle} for DIN A4 format. * /*from ww w .j a v a2s.c om*/ * @return {@link Rectangle} with A4 size *********************************** ************************************* */ private Rectangle setA4pagesize() { int page_w = 210; // dimensions of the page; A4 in mm int page_h = 297; int page_w_points = (int) ((page_w * 72) / 25.4); int page_h_points = (int) ((page_h * 72) / 25.4); // front page, it's always A4 Rectangle pageSize = new Rectangle(page_w_points, page_h_points); return pageSize; }
From source file:de.xirp.chart.ChartUtil.java
License:Open Source License
/** * Exports the given chart as PDF in the specified size. The * export is written to the given path.//from ww w . ja v a 2s.co m * * @param chart * The chart to export. * @param width * The desired width of the PDF. * @param height * The desired height of the PDF. * @param path * The path to write the PDF to. * @see org.jfree.chart.JFreeChart */ private static void exportPDF(JFreeChart chart, int width, int height, String path) { Document document = new Document(new Rectangle(width, height)); try { PdfWriter writer; writer = PdfWriter.getInstance(document, new FileOutputStream(path)); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(width, height); Graphics2D g2d = tp.createGraphics(width, height, new DefaultFontMapper()); Rectangle2D r2d = new Rectangle2D.Double(0, 0, width, height); chart.draw(g2d, r2d); g2d.dispose(); cb.addTemplate(tp, 0, 0); } catch (Exception e) { logClass.error("Error: " + e.getMessage() //$NON-NLS-1$ + Constants.LINE_SEPARATOR, e); } document.close(); }
From source file:fr.opensagres.odfdom.converter.pdf.internal.stylable.StylableDocument.java
License:Open Source License
public void applyStyles(Style style) { this.lastStyleApplied = style; StylePageLayoutProperties pageLayoutProperties = style.getPageLayoutProperties(); if (pageLayoutProperties != null) { // width/height Float width = pageLayoutProperties.getWidth(); Float height = pageLayoutProperties.getHeight(); if (width != null && height != null) { Rectangle pageSize = new Rectangle(width, height); super.setPageSize(pageSize); }// w ww . j a v a2 s .c om // margin if (pageLayoutProperties.getMarginTop() != null) { originMarginTop = pageLayoutProperties.getMarginTop(); } if (pageLayoutProperties.getMarginBottom() != null) { originMarginBottom = pageLayoutProperties.getMarginBottom(); } if (pageLayoutProperties.getMarginLeft() != null) { originMarginLeft = pageLayoutProperties.getMarginLeft(); } if (pageLayoutProperties.getMarginRight() != null) { originMarginRight = pageLayoutProperties.getMarginRight(); } super.setMargins(originMarginLeft, originMarginRight, originMarginTop, originMarginBottom); // orientation PageOrientation orientation = pageLayoutProperties.getOrientation(); if (orientation != null) { super.setOrientation(orientation); } } }
From source file:fr.opensagres.poi.xwpf.converter.pdf.internal.elements.StylableDocument.java
License:Open Source License
private void applySectPr(CTSectPr sectPr) { // Set page size CTPageSz pageSize = sectPr.getPgSz(); Rectangle pdfPageSize = new Rectangle(dxa2points(pageSize.getW()), dxa2points(pageSize.getH())); super.setPageSize(pdfPageSize); // Orientation PageOrientation orientation = XWPFUtils.getPageOrientation(pageSize.getOrient()); if (orientation != null) { switch (orientation) { case Landscape: super.setOrientation(fr.opensagres.xdocreport.itext.extension.PageOrientation.Landscape); break; case Portrait: super.setOrientation(fr.opensagres.xdocreport.itext.extension.PageOrientation.Portrait); break; }/*from www .ja v a 2 s. c om*/ } // Set page margin CTPageMar pageMar = sectPr.getPgMar(); if (pageMar != null) { super.setOriginalMargins(dxa2points(pageMar.getLeft()), dxa2points(pageMar.getRight()), dxa2points(pageMar.getTop()), dxa2points(pageMar.getBottom())); } }