List of usage examples for org.apache.pdfbox.pdmodel PDDocument getPage
public PDPage getPage(int pageIndex)
From source file:airviewer.BoxAnnotationMaker.java
License:Apache License
/** * * @param document//from www . java 2 s.c o m * @param arguments(lowerLeftX, lowerLeftY, width, height) * @return */ public static List<PDAnnotation> make(PDDocument document, ArrayList<String> arguments) { assert null != arguments && arguments.size() == 5; assert null != document; List<PDAnnotation> result; try { int pageNumber = parseInt(arguments.get(0)); float lowerLeftX = parseFloat(arguments.get(1)); float lowerLeftY = parseFloat(arguments.get(2)); float width = parseFloat(arguments.get(3)); float height = parseFloat(arguments.get(4)); String contents = ""; PDFont font = PDType1Font.HELVETICA_OBLIQUE; float fontSize = 16; // Or whatever font size you want. //float textWidth = font.getStringWidth(contents) * fontSize / 1000.0f; //float textHeight = 32; try { PDPage page = document.getPage(pageNumber); PDColor red = new PDColor(new float[] { 1, 0, 0 }, PDDeviceRGB.INSTANCE); PDBorderStyleDictionary borderThick = new PDBorderStyleDictionary(); borderThick.setWidth(72 / 12); // 12th inch PDRectangle position = new PDRectangle(); position.setLowerLeftX(lowerLeftX); position.setLowerLeftY(lowerLeftY); position.setUpperRightX(lowerLeftX + width); position.setUpperRightY(lowerLeftY + height); PDAnnotationSquareCircle aSquare = new PDAnnotationSquareCircle( PDAnnotationSquareCircle.SUB_TYPE_SQUARE); aSquare.setAnnotationName(new UID().toString()); aSquare.setContents(contents); aSquare.setColor(red); // Outline in red, not setting a fill PDColor fillColor = new PDColor(new float[] { .8f, .8f, .8f }, PDDeviceRGB.INSTANCE); aSquare.setInteriorColor(fillColor); aSquare.setBorderStyle(borderThick); aSquare.setRectangle(position); result = new ArrayList<>(page.getAnnotations()); // copy page.getAnnotations().add(aSquare); // The following lines are needed for PDFRenderer to render // annotations. Preview and Acrobat don't seem to need these. if (null == aSquare.getAppearance()) { aSquare.setAppearance(new PDAppearanceDictionary()); PDAppearanceStream annotationAppearanceStream = new PDAppearanceStream(document); position.setLowerLeftX(lowerLeftX - borderThick.getWidth() * 0.5f); position.setLowerLeftY(lowerLeftY - borderThick.getWidth() * 0.5f); position.setUpperRightX(lowerLeftX + width + borderThick.getWidth() * 0.5f); position.setUpperRightY(lowerLeftY + height + borderThick.getWidth() * 0.5f); annotationAppearanceStream.setBBox(position); annotationAppearanceStream.setMatrix(new AffineTransform()); annotationAppearanceStream.setResources(page.getResources()); try (PDPageContentStream appearanceContent = new PDPageContentStream(document, annotationAppearanceStream)) { Matrix transform = new Matrix(); appearanceContent.transform(transform); appearanceContent.addRect(lowerLeftX, lowerLeftY, width, height); appearanceContent.setLineWidth(borderThick.getWidth()); appearanceContent.setNonStrokingColor(fillColor); appearanceContent.setStrokingColor(red); appearanceContent.fillAndStroke(); appearanceContent.beginText(); // Center text vertically, left justified appearanceContent.newLineAtOffset(lowerLeftX, lowerLeftY + height * 0.5f - fontSize * 0.5f); appearanceContent.setFont(font, fontSize); appearanceContent.setNonStrokingColor(red); appearanceContent.showText(contents); appearanceContent.endText(); } aSquare.getAppearance().setNormalAppearance(annotationAppearanceStream); } //System.out.println(page.getAnnotations().toString()); } catch (IOException ex) { Logger.getLogger(DocumentCommandWrapper.class.getName()).log(Level.SEVERE, null, ex); result = null; } } catch (NumberFormatException | NullPointerException ex) { System.err.println("\tNon number encountered where floating point number expected."); result = null; } return result; }
From source file:airviewer.EllipseAnnotationMaker.java
License:Apache License
/** * /*from ww w . jav a 2 s . c om*/ * @param document * @param arguments(pageNumber, lowerLeftX, lowerLeftY, width, height, contents) * @return */ public static List<PDAnnotation> make(PDDocument document, ArrayList<String> arguments) { assert null != arguments && arguments.size() == 6; assert null != document; List<PDAnnotation> result; try { int pageNumber = parseInt(arguments.get(0)); float lowerLeftX = parseFloat(arguments.get(1)); float lowerLeftY = parseFloat(arguments.get(2)); float width = parseFloat(arguments.get(3)); float height = parseFloat(arguments.get(4)); String contents = arguments.get(5); PDFont font = PDType1Font.HELVETICA_OBLIQUE; final float fontSize = 16.0f; // Or whatever font size you want. //final float lineSpacing = 4.0f; width = max(width, font.getStringWidth(contents) * fontSize / 1000.0f); //final float textHeight = fontSize + lineSpacing; try { PDPage page = document.getPage(pageNumber); PDColor red = new PDColor(new float[] { 1, 0, 0 }, PDDeviceRGB.INSTANCE); PDColor black = new PDColor(new float[] { 0, 0, 0 }, PDDeviceRGB.INSTANCE); PDBorderStyleDictionary borderThick = new PDBorderStyleDictionary(); borderThick.setWidth(72 / 12); // 12th inch PDRectangle position = new PDRectangle(); position.setLowerLeftX(lowerLeftX); position.setLowerLeftY(lowerLeftY); position.setUpperRightX(lowerLeftX + width); position.setUpperRightY(lowerLeftY + height); PDAnnotationSquareCircle aCircle = new PDAnnotationSquareCircle( PDAnnotationSquareCircle.SUB_TYPE_CIRCLE); aCircle.setAnnotationName(new UID().toString()); aCircle.setContents(contents); PDColor fillColor = new PDColor(new float[] { .8f, .8f, .8f }, PDDeviceRGB.INSTANCE); aCircle.setInteriorColor(fillColor); aCircle.setColor(red); aCircle.setBorderStyle(borderThick); aCircle.setRectangle(position); result = new ArrayList<>(page.getAnnotations()); // Copy page.getAnnotations().add(aCircle); // The following lines are needed for PDFRenderer to render // annotations. Preview and Acrobat don't seem to need these. if (null == aCircle.getAppearance()) { aCircle.setAppearance(new PDAppearanceDictionary()); PDAppearanceStream annotationAppearanceStream = new PDAppearanceStream(document); position.setLowerLeftX(lowerLeftX - borderThick.getWidth() * 0.5f); position.setLowerLeftY(lowerLeftY - borderThick.getWidth() * 0.5f); position.setUpperRightX(lowerLeftX + width + borderThick.getWidth() * 0.5f); position.setUpperRightY(lowerLeftY + height + borderThick.getWidth() * 0.5f); annotationAppearanceStream.setBBox(position); annotationAppearanceStream.setMatrix(new AffineTransform()); annotationAppearanceStream.setResources(page.getResources()); try (PDPageContentStream appearanceContent = new PDPageContentStream(document, annotationAppearanceStream)) { Matrix transform = new Matrix(); appearanceContent.transform(transform); appearanceContent.moveTo(lowerLeftX, lowerLeftY + height * 0.5f); appearanceContent.curveTo(lowerLeftX, lowerLeftY + height * 0.75f, lowerLeftX + width * 0.25f, lowerLeftY + height, lowerLeftX + width * 0.5f, lowerLeftY + height); appearanceContent.curveTo(lowerLeftX + width * 0.75f, lowerLeftY + height, lowerLeftX + width, lowerLeftY + height * 0.75f, lowerLeftX + width, lowerLeftY + height * 0.5f); appearanceContent.curveTo(lowerLeftX + width, lowerLeftY + height * 0.25f, lowerLeftX + width * 0.75f, lowerLeftY, lowerLeftX + width * 0.5f, lowerLeftY); appearanceContent.curveTo(lowerLeftX + width * 0.25f, lowerLeftY, lowerLeftX, lowerLeftY + height * 0.25f, lowerLeftX, lowerLeftY + height * 0.5f); appearanceContent.setLineWidth(borderThick.getWidth()); appearanceContent.setNonStrokingColor(fillColor); appearanceContent.setStrokingColor(red); appearanceContent.fillAndStroke(); appearanceContent.moveTo(0, 0); appearanceContent.beginText(); appearanceContent.setNonStrokingColor(black); // Center text vertically, left justified appearanceContent.newLineAtOffset(lowerLeftX + borderThick.getWidth(), lowerLeftY + height * 0.5f - fontSize * 0.5f); appearanceContent.setFont(font, fontSize); appearanceContent.showText(contents); appearanceContent.endText(); } aCircle.getAppearance().setNormalAppearance(annotationAppearanceStream); } } catch (IOException ex) { Logger.getLogger(DocumentCommandWrapper.class.getName()).log(Level.SEVERE, null, ex); result = null; } } catch (NumberFormatException | NullPointerException ex) { System.err.println("Non number encountered where floating point number expected."); result = null; } catch (IOException ex) { Logger.getLogger(EllipseAnnotationMaker.class.getName()).log(Level.SEVERE, null, ex); result = null; } return result; }
From source file:airviewer.TextAnnotationMaker.java
License:Apache License
/** * /*from w w w . jav a 2s. com*/ * @param document * @param arguments(pageNumber, lowerLeftX, lowerLeftY); String contents * @return */ public static List<PDAnnotation> make(PDDocument document, ArrayList<String> arguments) { assert null != arguments && arguments.size() == 4; assert null != document; List<PDAnnotation> result; try { int pageNumber = parseInt(arguments.get(0)); float lowerLeftX = parseFloat(arguments.get(1)); float lowerLeftY = parseFloat(arguments.get(2)); String contents = arguments.get(3); PDFont font = PDType1Font.HELVETICA_OBLIQUE; final float fontSize = 16.0f; // Or whatever font size you want. final float lineSpacing = 4.0f; float width = font.getStringWidth(contents) * fontSize / 1000.0f; // font.getStringWidth(contents) returns thousanths of PS point final float textHeight = fontSize + lineSpacing; try { PDPage page = document.getPage(pageNumber); PDColor red = new PDColor(new float[] { 1, 0, 0 }, PDDeviceRGB.INSTANCE); PDBorderStyleDictionary borderThick = new PDBorderStyleDictionary(); borderThick.setWidth(72 / 12); // 12th inch PDRectangle position = new PDRectangle(); position.setLowerLeftX(lowerLeftX); position.setLowerLeftY(lowerLeftY); position.setUpperRightX(lowerLeftX + width); position.setUpperRightY(lowerLeftY + textHeight); PDAnnotationSquareCircle aSquare = new PDAnnotationSquareCircle( PDAnnotationSquareCircle.SUB_TYPE_SQUARE); aSquare.setAnnotationName(new UID().toString()); aSquare.setContents(contents); PDColor fillColor = new PDColor(new float[] { .8f, .8f, .8f }, PDDeviceRGB.INSTANCE); aSquare.setInteriorColor(fillColor); aSquare.setRectangle(position); result = new ArrayList<>(page.getAnnotations()); // copy page.getAnnotations().add(aSquare); // The following lines are needed for PDFRenderer to render // annotations. Preview and Acrobat don't seem to need these. if (null == aSquare.getAppearance()) { aSquare.setAppearance(new PDAppearanceDictionary()); PDAppearanceStream annotationAppearanceStream = new PDAppearanceStream(document); position.setLowerLeftX(lowerLeftX - borderThick.getWidth() * 0.5f); position.setLowerLeftY(lowerLeftY - borderThick.getWidth() * 0.5f); position.setUpperRightX(lowerLeftX + width + borderThick.getWidth() * 0.5f); position.setUpperRightY(lowerLeftY + textHeight + borderThick.getWidth() * 0.5f); annotationAppearanceStream.setBBox(position); annotationAppearanceStream.setMatrix(new AffineTransform()); annotationAppearanceStream.setResources(page.getResources()); try (PDPageContentStream appearanceContent = new PDPageContentStream(document, annotationAppearanceStream)) { Matrix transform = new Matrix(); appearanceContent.transform(transform); appearanceContent.addRect(lowerLeftX, lowerLeftY, width, textHeight); appearanceContent.setNonStrokingColor(fillColor); appearanceContent.fill(); appearanceContent.beginText(); // Center text vertically, left justified appearanceContent.newLineAtOffset(lowerLeftX, lowerLeftY + textHeight * 0.5f - fontSize * 0.5f); appearanceContent.setFont(font, fontSize); appearanceContent.setNonStrokingColor(red); appearanceContent.showText(contents); appearanceContent.endText(); } aSquare.getAppearance().setNormalAppearance(annotationAppearanceStream); } //System.out.println(page.getAnnotations().toString()); } catch (IOException ex) { Logger.getLogger(DocumentCommandWrapper.class.getName()).log(Level.SEVERE, null, ex); result = null; } } catch (NumberFormatException | NullPointerException ex) { System.err.println("Non number encountered where floating point number expected."); result = null; } catch (IOException ex) { Logger.getLogger(TextAnnotationMaker.class.getName()).log(Level.SEVERE, null, ex); result = null; } return result; }
From source file:at.gv.egiz.pdfas.lib.impl.pdfbox2.positioning.Positioning.java
License:EUPL
/** * Sets the width of the table according to the layout of the document and * calculates the y position where the PDFPTable should be placed. * * @param pdfDataSource//from w ww .j a v a2 s . c om * The PDF document. * @param pdf_table * The PDFPTable to be placed. * @param settings * @return Returns the position where the PDFPTable should be placed. * @throws PdfAsException * F.e. */ public static PositioningInstruction adjustSignatureTableandCalculatePosition(final PDDocument pdfDataSource, IPDFVisualObject pdf_table, TablePos pos, ISettings settings) throws PdfAsException { PdfBoxUtils.checkPDFPermissions(pdfDataSource); // get pages of currentdocument int doc_pages = pdfDataSource.getNumberOfPages(); int page = doc_pages; boolean make_new_page = pos.isNewPage(); if (!(pos.isNewPage() || pos.isPauto())) { // we should posit signaturtable on this page page = pos.getPage(); // System.out.println("XXXXPAGE="+page+" doc_pages="+doc_pages); if (page > doc_pages) { make_new_page = true; page = doc_pages; // throw new PDFDocumentException(227, "Page number is to big(=" // + page+ // ") cannot be parsed."); } } PDPage pdPage = pdfDataSource.getPage(page - 1); PDRectangle cropBox = pdPage.getCropBox(); // fallback to MediaBox if Cropbox not available! if (cropBox == null) { cropBox = pdPage.getCropBox(); } if (cropBox == null) { cropBox = pdPage.getCropBox(); } // getPagedimensions // Rectangle psize = reader.getPageSizeWithRotation(page); // int page_rotation = reader.getPageRotation(page); // Integer rotation = pdPage.getRotation(); // int page_rotation = rotation.intValue(); int rotation = pdPage.getRotation(); logger.debug("Original CropBox: " + cropBox.toString()); cropBox = rotateBox(cropBox, rotation); logger.debug("Rotated CropBox: " + cropBox.toString()); float page_width = cropBox.getWidth(); float page_height = cropBox.getHeight(); logger.debug("CropBox width: " + page_width); logger.debug("CropBox heigth: " + page_height); // now we can calculate x-position float pre_pos_x = SIGNATURE_MARGIN_HORIZONTAL; if (!pos.isXauto()) { // we do have absolute x pre_pos_x = pos.getPosX(); } // calculate width // center float pre_width = page_width - 2 * pre_pos_x; if (!pos.isWauto()) { // we do have absolute width pre_width = pos.getWidth(); if (pos.isXauto()) { // center x pre_pos_x = (page_width - pre_width) / 2; } } final float pos_x = pre_pos_x; final float width = pre_width; // Signatur table dimensions are complete pdf_table.setWidth(width); pdf_table.fixWidth(); // pdf_table.setTotalWidth(width); // pdf_table.setLockedWidth(true); final float table_height = pdf_table.getHeight(); // now check pos_y float pos_y = pos.getPosY(); // in case an absolute y position is already given OR // if the table is related to an invisible signature // there is no need for further calculations // (fixed adding new page in case of invisible signatures) if (!pos.isYauto() || table_height == 0) { // we do have y-position too --> all parameters but page ok if (make_new_page) { page++; } return new PositioningInstruction(make_new_page, page, pos_x, pos_y, pos.rotation); } // pos_y is auto if (make_new_page) { // ignore footer in new page page++; pos_y = page_height - SIGNATURE_MARGIN_VERTICAL; return new PositioningInstruction(make_new_page, page, pos_x, pos_y, pos.rotation); } // up to here no checks have to be made if Tablesize and Pagesize are // fit // Now we have to getfreespace in page and reguard footerline float footer_line = pos.getFooterLine(); // float pre_page_length = PDFUtilities.calculatePageLength(pdfDataSource, // page - 1, page_height - footer_line, /* page_rotation, */ // legacy32, legacy40); float pre_page_length = Float.NEGATIVE_INFINITY; try { pre_page_length = PDFUtilities.getMaxYPosition(pdfDataSource, page - 1, pdf_table, SIGNATURE_MARGIN_VERTICAL, footer_line, settings); //pre_page_length = PDFUtilities.getFreeTablePosition(pdfDataSource, page-1, pdf_table,SIGNATURE_MARGIN_VERTICAL); } catch (IOException e) { logger.warn("Could not determine page length, using -INFINITY"); } if (pre_page_length == Float.NEGATIVE_INFINITY) { // we do have an empty page or nothing in area above footerline pre_page_length = page_height; // no text --> SIGNATURE_BORDER pos_y = page_height - SIGNATURE_MARGIN_VERTICAL; if (pos_y - footer_line <= table_height) { make_new_page = true; if (!pos.isPauto()) { // we have to correct pagenumber page = pdfDataSource.getNumberOfPages(); } page++; // no text --> SIGNATURE_BORDER pos_y = page_height - SIGNATURE_MARGIN_VERTICAL; } return new PositioningInstruction(make_new_page, page, pos_x, pos_y, pos.rotation); } final float page_length = pre_page_length; // we do have text take SIGNATURE_MARGIN pos_y = page_height - page_length - SIGNATURE_MARGIN_VERTICAL; if (pos_y - footer_line <= table_height) { make_new_page = true; if (!pos.isPauto()) { // we have to correct pagenumber in case of absolute page and // not enough // space page = pdfDataSource.getNumberOfPages(); } page++; // no text --> SIGNATURE_BORDER pos_y = page_height - SIGNATURE_MARGIN_VERTICAL; } return new PositioningInstruction(make_new_page, page, pos_x, pos_y, pos.rotation); }
From source file:at.knowcenter.wag.egov.egiz.pdfbox2.pdf.PDFUtilities.java
License:EUPL
public static float getMaxYPosition(PDDocument pdfDataSource, int page, IPDFVisualObject pdfTable, float signatureMarginVertical, float footer_line, ISettings settings) throws IOException { PositioningRenderer renderer = new PositioningRenderer(pdfDataSource); //BufferedImage bim = renderer.renderImage(page); int width = (int) pdfDataSource.getPage(page).getCropBox().getWidth(); int height = (int) pdfDataSource.getPage(page).getCropBox().getHeight(); BufferedImage bim = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D graphics = bim.createGraphics(); graphics.setBackground(MAGIC_COLOR); renderer.renderPageToGraphics(page, graphics); Color bgColor = MAGIC_COLOR;/*w w w. j a va 2 s . c om*/ if ("true".equals(settings.getValue(BG_COLOR_DETECTION))) { //only used if background color should be determined automatically bgColor = determineBackgroundColor(bim); } int yCoord = bim.getHeight() - 1 - (int) footer_line; for (int row = yCoord; row >= 0; row--) { for (int col = 0; col < bim.getWidth(); col++) { int val = bim.getRGB(col, row); if (val != bgColor.getRGB()) { yCoord = row; row = -1; break; } } } String outFile = settings.getValue(SIG_PLACEMENT_DEBUG_OUTPUT); if (outFile != null) { ImageIOUtil.writeImage(bim, outFile, 72); } return yCoord; }
From source file:boxtable.table.Table.java
License:Apache License
/** * Starts a new page with the same size as the last one * /*from w w w.ja va 2 s . co m*/ * @param document * The document the table is rendered to * @param stream * The PDPageContentStream used to render the table up to now (will be closed after calling this method) * @return A new PDPageContentStream for rendering to the new page * @throws IOException * If writing to the streams fails */ private PDPageContentStream newPage(final PDDocument document, final PDPageContentStream stream) throws IOException { final PDRectangle pageSize = document.getPage(document.getNumberOfPages() - 1).getMediaBox(); handleEvent(EventType.END_PAGE, document, stream, 0, pageSize.getHeight(), pageSize.getWidth(), pageSize.getHeight()); stream.close(); final PDPage page = new PDPage(pageSize); document.addPage(page); PDPageContentStream newStream = new PDPageContentStream(document, page, AppendMode.APPEND, true); handleEvent(EventType.BEGIN_PAGE, document, newStream, 0, pageSize.getHeight(), pageSize.getWidth(), pageSize.getHeight()); return newStream; }
From source file:boxtable.table.Table.java
License:Apache License
/** * Renders this table to a document//from w ww.j av a2 s . c o m * * @param document * The document this table will be rendered to * @param width * The width of the table * @param left * The left edge of the table * @param top * The top edge of the table * @param paddingTop * The amount of free space at the top of a new page (if a page break is necessary) * @param paddingBottom * The minimal amount of free space at the bottom of the page before inserting a page break * @return The bottom edge of the last rendered table part * @throws IOException * If writing to the document fails */ @SuppressWarnings("resource") public float render(final PDDocument document, final float width, final float left, float top, final float paddingTop, final float paddingBottom) throws IOException { float yPos = top; final PDPage page = document.getPage(document.getNumberOfPages() - 1); final PDRectangle pageSize = page.getMediaBox(); PDPageContentStream stream = new PDPageContentStream(document, page, AppendMode.APPEND, true); float height = getHeight(width); if (height > pageSize.getHeight() - paddingTop - paddingBottom) { final float[] colWidths = getColumnWidths(width); for (int i = 0; i < rows.size(); ++i) { if (rows.get(i).getHeight(colWidths) > yPos - paddingBottom) { drawBorder(stream, left, top, width, top - yPos); stream = newPage(document, stream); top = pageSize.getHeight() - paddingTop; yPos = top; yPos = renderRows(document, stream, 0, getNumHeaderRows(), width, left, yPos); i = Math.max(i, getNumHeaderRows()); } yPos = renderRows(document, stream, i, i + 1, width, left, yPos); } drawBorder(stream, left, top, width, top - yPos); handleEvent(EventType.AFTER_TABLE, document, stream, left, top, width, top - yPos); } else { if (height > top - paddingBottom) { stream = newPage(document, stream); top = pageSize.getHeight() - paddingTop; yPos = top; } yPos = renderRows(document, stream, 0, -1, width, left, yPos); drawBorder(stream, left, top, width, top - yPos); handleEvent(EventType.AFTER_TABLE, document, stream, left, top, width, top - yPos); } stream.close(); return yPos; }
From source file:com.amolik.misc.ExtractTextByArea.java
License:Apache License
/** * This will print the documents text in a certain area. * * @param args The command line arguments. * * @throws IOException If there is an error parsing the document. *//* w ww . j av a 2 s . c om*/ public static void main(String[] args) throws IOException { //args[0]= "E:\\Automation\\uphillit\\Fiscal_demo_data.pdf"; // if( args.length != 1 ) // { // usage(); // } // else // { PDDocument document = null; try { document = PDDocument.load(new File("E:\\Automation\\uphillit\\Fiscal_demo_data.pdf")); int numberOfPages = document.getNumberOfPages(); if (numberOfPages > 0) { PDPage page = (PDPage) document.getPages().get(0); System.out.println(page.getContents()); } PDFTextStripperByArea stripper = new PDFTextStripperByArea(); stripper.setSortByPosition(true); Rectangle rect = new Rectangle(3, 1, 600, 6000); stripper.addRegion("class1", rect); PDPage firstPage = document.getPage(0); stripper.extractRegions(firstPage); System.out.println("Text in the area:" + rect); System.out.println(stripper.getTextForRegion("class1")); } finally { if (document != null) { document.close(); } } // } }
From source file:com.bgh.myopeninvoice.jsf.jsfbeans.InvoiceBean.java
License:Apache License
public String getImageAttachment(AttachmentEntity attachmentEntity) throws IOException, ImageReadException { if (attachmentEntity != null && attachmentEntity.getContent().length > 0) { if (attachmentEntity.getLoadProxy()) { return "/images/" + attachmentEntity.getFileExtension() + ".png"; } else {/*from ww w .j a v a 2s. c om*/ selectedAttachmentEntity = attachmentEntity; ImageFormat mimeType = Sanselan.guessFormat(attachmentEntity.getContent()); if (mimeType != null && !"UNKNOWN".equalsIgnoreCase(mimeType.name)) { return "data:image/" + mimeType.extension.toLowerCase() + ";base64," + Base64.getEncoder().encodeToString(attachmentEntity.getContent()); } else if (attachmentEntity.getImageData() != null && attachmentEntity.getImageData().length > 0) { return "data:image/png;base64," + Base64.getEncoder().encodeToString(attachmentEntity.getImageData()); } else if ("pdf".equalsIgnoreCase(attachmentEntity.getFileExtension())) { ByteArrayOutputStream baos = null; PDDocument document = null; try { document = PDDocument.load(attachmentEntity.getContent()); final PDPage page = document.getPage(0); PDFRenderer pdfRenderer = new PDFRenderer(document); final BufferedImage bufferedImage = pdfRenderer.renderImage(0); baos = new ByteArrayOutputStream(); ImageIO.write(bufferedImage, "png", baos); baos.flush(); attachmentEntity.setImageData(baos.toByteArray()); } finally { if (document != null) { document.close(); } if (baos != null) { baos.close(); } } return "data:image/png;base64," + Base64.getEncoder().encodeToString(attachmentEntity.getImageData()); } else { return null; } } } else if (selectedAttachmentEntity != null && selectedAttachmentEntity.getImageData() != null && selectedAttachmentEntity.getImageData().length > 0) { return "data:image/png;base64," + Base64.getEncoder().encodeToString(selectedAttachmentEntity.getImageData()); } else { return null; } }
From source file:com.encodata.PDFSigner.PDFSigner.java
public void createPDFFromImage(String inputFile, String imagePath, String outputFile, String x, String y, String width, String height, CallbackContext callbackContext) throws IOException { if (inputFile == null || imagePath == null || outputFile == null) { callbackContext.error("Expected localFile and remoteFile."); } else {//w w w . j av a2 s . co m // the document PDDocument doc = null; try { doc = PDDocument.load(new File(inputFile)); //we will add the image to the first page. PDPage page = doc.getPage(0); // createFromFile is the easiest way with an image file // if you already have the image in a BufferedImage, // call LosslessFactory.createFromImage() instead PDImageXObject pdImage = PDImageXObject.createFromFile(imagePath, doc); PDPageContentStream contentStream = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true); // contentStream.drawImage(ximage, 20, 20 ); // better method inspired by http://stackoverflow.com/a/22318681/535646 // reduce this value if the image is too large float scale = 1f; contentStream.drawImage(pdImage, Float.parseFloat(x), Float.parseFloat(y), Float.parseFloat(width) * scale, Float.parseFloat(height) * scale); contentStream.close(); doc.save(outputFile); callbackContext.success(outputFile); } catch (Exception e) { callbackContext.error(e.toString()); } finally { if (doc != null) { doc.close(); } } } }