List of usage examples for com.lowagie.text Image getInstance
public static Image getInstance(Image image)
From source file:cz.incad.kramerius.rest.api.k5.client.pdf.PDFResource.java
License:Open Source License
private static StreamingOutput streamingOutput(final File file, final String format) { return new StreamingOutput() { public void write(OutputStream output) throws IOException, WebApplicationException { try { Rectangle formatRect = formatRect(format); Document document = new Document(formatRect); PdfWriter.getInstance(document, output); document.open();/*from w w w . j a v a 2 s . c o m*/ Image image = Image.getInstance(file.toURI().toURL()); image.scaleToFit( document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin(), document.getPageSize().getHeight() - document.topMargin() - document.bottomMargin()); document.add(image); document.close(); } catch (Exception e) { throw new WebApplicationException(e); } finally { if (file != null) file.delete(); } } }; }
From source file:daoimpl.CustomizedDocumentsView.java
public void preProcessPDF(Object document) throws IOException, BadElementException, DocumentException { Document pdf = (Document) document; pdf.open();/*from w w w .j av a2s. c o m*/ 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:datasoul.servicelist.ServiceListExporterDocument.java
License:Open Source License
private LinkedList<Paragraph> addChordsShape(ArrayList<String> chordsName) throws DocumentException { ChordsDB chordsDB = ChordsDB.getInstance(); String notCatalogued = ""; LinkedList<Chunk> images = new LinkedList<Chunk>(); LinkedList<File> filesToDelete = new LinkedList<File>(); LinkedList<Paragraph> ret = new LinkedList<Paragraph>(); for (int i = 0; i < chordsName.size(); i++) { Chord chord = chordsDB.getChordByName(chordsName.get(i)); if (chord != null) { ChordShapePanel csp = new ChordShapePanel(2, chord.getName(), chord.getShape()); BufferedImage im = csp.createImage(); try { File tmp = File.createTempFile("datasoul-img", ".png"); tmp.deleteOnExit();/* w ww . j a va2s .c o m*/ filesToDelete.add(tmp); ImageIO.write(im, "png", tmp); Chunk c = new Chunk(Image.getInstance(tmp.getAbsolutePath()), 0, 0, false); images.add(c); } catch (IOException e) { JOptionPane.showMessageDialog(null, java.util.ResourceBundle .getBundle("datasoul/internationalize").getString("INTERNAL ERROR: ") + e.getMessage()); } } else { notCatalogued += chordsName.get(i); } } Paragraph p = new Paragraph(); if (!images.isEmpty()) { for (Chunk c : images) { p.add(c); } p.setLeading(images.getFirst().getImage().getScaledHeight()); p.setKeepTogether(true); } ret.add(p); if (!notCatalogued.equals("")) { p = new Paragraph( java.util.ResourceBundle.getBundle("datasoul/internationalize") .getString("THE FOLLOWING CHORDS ARE NOT CATALOGED: ") + notCatalogued, FontFactory.getFont(FontFactory.HELVETICA, 8)); ret.add(p); } for (File f : filesToDelete) { try { f.delete(); } catch (Exception e) { //ignore, it will be deleted on exit } } return ret; }
From source file:datasoul.servicelist.ServiceListExporterSlides.java
License:Open Source License
public void addEmptySlide() throws DocumentException { try {/* w w w . j a v a 2 s. co m*/ File tmp = File.createTempFile("datasoul-img-bg", ".png"); tmp.deleteOnExit(); ImageIO.write(render.getBackgroundImage(), "png", tmp); deleteOnDispose.add(tmp.getAbsolutePath()); document.add(Image.getInstance(tmp.getAbsolutePath())); slideCount++; } catch (IOException e) { e.printStackTrace(); slideCount = -1; } }
From source file:de.appplant.cordova.plugin.printer.Printer.java
License:Apache License
/** * Slices the screenshot into pages, merges those into a single pdf * and saves it in the public accessible /sdcard dir. */// ww w .j a v a 2 s . c o m private File saveWebViewAsPdf(Bitmap screenshot) { try { File sdCard = Environment.getExternalStorageDirectory(); File dir = new File(sdCard.getAbsolutePath() + "/" + this.publicTmpDir + "/"); dir.mkdirs(); File file; FileOutputStream stream; double pageWidth = PageSize.A4.getWidth() * 0.85; // width of the image is 85% of the page double pageHeight = PageSize.A4.getHeight() * 0.80; // max height of the image is 80% of the page double pageHeightToWithRelation = pageHeight / pageWidth; // e.g.: 1.33 (4/3) Bitmap currPage; int totalSize = screenshot.getHeight(); int currPos = 0; int currPageCount = 0; int sliceWidth = screenshot.getWidth(); int sliceHeight = (int) Math.round(sliceWidth * pageHeightToWithRelation); while (totalSize > currPos && currPageCount < 100) // max 100 pages { currPageCount++; Log.v(LOG_TAG, "Creating page nr. " + currPageCount); // slice bitmap currPage = Bitmap.createBitmap(screenshot, 0, currPos, sliceWidth, (int) Math.min(sliceHeight, totalSize - currPos)); // save page as png stream = new FileOutputStream(new File(dir, "print-page-" + currPageCount + ".png")); currPage.compress(Bitmap.CompressFormat.PNG, 100, stream); stream.close(); // move current position indicator currPos += sliceHeight; } // create pdf Log.v(LOG_TAG, "Creating pdf"); Document document = new Document(); File filePdf = new File(dir, this.printTitle + ".pdf"); // change the output name of the pdf here PdfWriter.getInstance(document, new FileOutputStream(filePdf)); document.open(); for (int i = 1; i <= currPageCount; ++i) { Log.v(LOG_TAG, "Adding page nr. " + i + " to the pdf file."); file = new File(dir, "print-page-" + i + ".png"); Image image = Image.getInstance(file.getAbsolutePath()); image.scaleToFit((float) pageWidth, 9999); image.setAlignment(Element.ALIGN_CENTER); document.add(image); document.newPage(); } document.close(); // delete tmp image files for (int i = 1; i <= currPageCount; ++i) { file = new File(dir, "print-page-" + i + ".png"); file.delete(); } return filePdf; } catch (IOException e) { Log.e(LOG_TAG, "ERROR: " + e.getMessage()); e.printStackTrace(); // return error answer to cordova PluginResult result = new PluginResult(PluginResult.Status.ERROR, e.getMessage()); result.setKeepCallback(false); ctx.sendPluginResult(result); } catch (DocumentException e) { Log.e(LOG_TAG, "ERROR: " + e.getMessage()); e.printStackTrace(); // return error answer to cordova PluginResult result = new PluginResult(PluginResult.Status.ERROR, e.getMessage()); result.setKeepCallback(false); ctx.sendPluginResult(result); } Log.e(LOG_TAG, "Uncaught ERROR!"); return null; }
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 ww.j a v a2s.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.japes.text.PdfCreator.java
License:Open Source License
public String exportToPdf(byte[] imgArray) { String filename;/*from ww w. j av a 2 s. c o m*/ Document document = new Document(); Image img = null; Calendar cal = Calendar.getInstance(); filename = "chart_" + cal.get(Calendar.YEAR) + cal.get(Calendar.MONTH) + cal.get(Calendar.DAY_OF_MONTH) + "_" + cal.get(Calendar.HOUR_OF_DAY) + cal.get(Calendar.MINUTE) + ".pdf"; try { img = Image.getInstance(imgArray); } catch (MalformedURLException e) { return e.getMessage(); } catch (IOException e) { return e.getMessage(); } catch (BadElementException e) { return e.getMessage(); } img.setAlignment(Image.ALIGN_CENTER); try { // step 2: // we create a writer that listens to the document // and directs a PDF-stream to a file PdfWriter.getInstance(document, new FileOutputStream(filename)); // step 3: we open the document document.open(); // step 4: we add a paragraph to the document document.add(img); } catch (DocumentException de) { return de.getMessage(); } catch (IOException ioe) { return ioe.getMessage(); } // step 5: we close the document document.close(); return filename; }
From source file:de.unigoettingen.sub.commons.contentlib.pdflib.PDFManager.java
License:Apache License
/****************************************************************************************************** * Adds the all pages.//ww w .ja va2 s . c om * * @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
/*************************************************************************************************************** * Generates {@link Image} from {@link ImageInterpreter} that we can embedd in PDF. Used by * {@link PDFManager#addAllPages(PdfPageSize, PdfWriter, Document, Watermark)} * //from w ww . j a v a 2 s. c om * @param myInterpreter {@link ImageInterpreter} * @param preferredEmbeddingType {@link Embedd} * * @param errorPage {@link Boolean} is this an errorpage ? * @param watermark {@link Watermark} * @param errorUrl {@link URL} link to image, that caused the error * * @return {@link Image} or null * * @throws IOException * @throws MalformedURLException * @throws BadElementException * * @throws ImageInterpreterException - if we can't generate Watermark * @throws ImageManipulatorException - if we can't generate Watermark ***************************************************************************************************************/ private Image generatePdfImageFromInterpreter(ImageInterpreter myInterpreter, Embedd preferredEmbeddingType, boolean errorPage, Watermark watermark, URL errorUrl) throws BadElementException, MalformedURLException, IOException, PDFManagerException, ImageInterpreterException, ImageManipulatorException { ByteArrayOutputStream bytesoutputstream = new ByteArrayOutputStream(); RenderedImage ri = null; switch (preferredEmbeddingType) { case ORIGBYTESTREAM: // if the bytestream is directly embeddable // should be embedded, but is it the bytestream // embeddable? if (myInterpreter.pdfBytestreamEmbeddable()) { Image image = Image.getInstance(myInterpreter.getImageByteStream()); myInterpreter.clear(); return image; } else { return null; } // ---------------------------------------------------------------------------------------------------- case JPEG: // it is NOT directly embeddable! if (myInterpreter.getColordepth() <= 1) { return null; } ri = myInterpreter.getRenderedImage(); // if there is an error - write error watermark! if (errorPage) { watermark = getNoImageErrorWatermark(errorUrl.toString()); ri = addwatermark(ri, watermark, ImageManager.TOP); myInterpreter.setHeight(myInterpreter.getHeight() + watermark.getRenderedImage().getHeight()); } else if (watermark != null) { try { ri = addwatermark(ri, watermark, 2); myInterpreter.setHeight(myInterpreter.getHeight() + watermark.getRenderedImage().getHeight()); } catch (NullPointerException e) { throw new PDFManagerException("Error while loading watermark"); } } try { writeJpegFromRenderedImageToStream(bytesoutputstream, ri, preferredEmbeddingType, myInterpreter); } catch (NullPointerException e) { throw new PDFManagerException("Error while rendering Image"); } break; // ---------------------------------------------------------------------------------------------------- case LOSSLESSJPEG2000: if (myInterpreter.getColordepth() > 1) { ri = myInterpreter.getRenderedImage(); writeJpegFromRenderedImageToStream(bytesoutputstream, ri, preferredEmbeddingType, myInterpreter); } else { return null; } break; case LOSSYJPEG2000: if (myInterpreter.getColordepth() > 1) { ri = myInterpreter.getRenderedImage(); writeJpegFromRenderedImageToStream(bytesoutputstream, ri, preferredEmbeddingType, myInterpreter); } else { return null; } break; // ---------------------------------------------------------------------------------------------------- case TIFFG4: if (myInterpreter.getColordepth() > 1) { // it's not a bitonal image return null; } else { TiffInterpreter tiffint = new TiffInterpreter(); tiffint.setXResolution(myInterpreter.getXResolution()); tiffint.setYResolution(myInterpreter.getYResolution()); try { tiffint.setWriterCompressionType(TiffInterpreter.COMPRESSION_CCITTFAX4); } catch (ParameterNotSupportedException e) { // should never happen, as the TiffInterpreter // supports this // kind of compression LOGGER.warn("Can't create TIFF G4 compressed image for embedding into PDF", e); } tiffint.writeToStream(null, bytesoutputstream); } break; default: LOGGER.error("Preferred embedding type does not match any of the supported types"); } myInterpreter.clear(); ri = null; byte[] returnbyteArray = bytesoutputstream.toByteArray(); if (bytesoutputstream != null) { bytesoutputstream.flush(); bytesoutputstream.close(); } Image image = Image.getInstance(returnbyteArray); returnbyteArray = null; return image; }
From source file:de.unigoettingen.sub.commons.contentlib.pdflib.PDFTitlePage.java
License:Apache License
/************************************************************************************ * render image for titlepage/* www .j ava 2 s . c o m*/ * * @param pdftpi the {@link PDFTitlePageImage} which shoud be renderd * @param pdfdoc the {@link com.lowagie.text.Document} where the titlepage shoud be rendered ************************************************************************************/ private void renderImage(PDFTitlePageImage pdftpi, com.lowagie.text.Document pdfdoc) throws DocumentException { try { Image img = Image.getInstance(pdftpi.getFilename()); // calculate the absolute position float absposx = pdftpi.getXCoordinate() * 72f / 2.54f; float absposy = pdftpi.getYCoordinate() * 72f / 2.54f; img.setAbsolutePosition(absposx, absposy); if (pdftpi.getScalefactor() != 0) { img.scalePercent(pdftpi.getScalefactor()); // scale image (in // percent) } pdfdoc.add(img); } catch (MalformedURLException mue) { LOGGER.error("WARNING: Can't read image " + pdftpi.getFilename() + " for PDF title page, invalid URL"); } catch (IOException ioe) { LOGGER.error( "WARNING: Can't read image:" + pdftpi.getFilename() + " for PDF title page - IO Exception"); } }