List of usage examples for org.apache.pdfbox.pdmodel PDPageTree get
public PDPage get(int index)
From source file:at.gv.egiz.pdfas.lib.impl.stamping.pdfbox2.PDFAsVisualSignatureDesigner.java
License:EUPL
/** * Each page of document can be different sizes. * //from w w w . j a v a 2s .c o m * @param document * @param page */ private void calculatePageSize(PDDocument document, int page, boolean newpage) { if (page < 1) { throw new IllegalArgumentException("First page of pdf is 1, not " + page); } PDPageTree pages = document.getDocumentCatalog().getPages(); if (newpage) { PDPage lastPage = (PDPage) pages.get(pages.getCount() - 1); PDRectangle mediaBox = lastPage.getMediaBox(); pageRotation = lastPage.getRotation() % 360; if (pageRotation == 90 || pageRotation == 270) { this.pageHeight(mediaBox.getWidth()); this.pageWidth = mediaBox.getHeight(); } else { this.pageHeight(mediaBox.getHeight()); this.pageWidth = mediaBox.getWidth(); } } else { PDPage firstPage = (PDPage) pages.get(page - 1); PDRectangle mediaBox = firstPage.getMediaBox(); pageRotation = firstPage.getRotation() % 360; if (pageRotation == 90 || pageRotation == 270) { this.pageHeight(mediaBox.getWidth()); this.pageWidth = mediaBox.getHeight(); } else { this.pageHeight(mediaBox.getHeight()); this.pageWidth = mediaBox.getWidth(); } } float x = this.pageWidth; float y = 0; this.pageWidth = this.pageWidth + y; float tPercent = (100 * y / (x + y)); this.imageSizeInPercents = 100 - tPercent; }
From source file:at.gv.egiz.pdfas.lib.impl.stamping.pdfbox2.PDFAsVisualSignatureDesigner.java
License:EUPL
public PDPage getSignaturePage() { if (page < 1) { throw new IllegalArgumentException("First page of pdf is 1, not " + page); }/*from w w w. ja va 2 s . c o m*/ PDPage pdPage = null; PDPageTree pages = document.getDocumentCatalog().getPages(); if (newpage) { pdPage = new PDPage(); } else { pdPage = (PDPage) pages.get(page - 1); } return pdPage; }
From source file:at.gv.egiz.pdfas.lib.impl.stamping.pdfbox2.PDFAsVisualSignatureProperties.java
License:EUPL
public PDFAsVisualSignatureProperties(ISettings settings, PDFBOXObject object, PdfBoxVisualObject visObj, PositioningInstruction pos, SignatureProfileSettings signatureProfileSettings) { this.settings = settings; this.signatureProfileSettings = signatureProfileSettings; try {// ww w . j a va 2 s. co m main = visObj.getTable(); } catch (Throwable e) { e.printStackTrace(); } this.rotationAngle = pos.getRotation(); try { origDoc = object.getDocument(); designer = new PDFAsVisualSignatureDesigner(origDoc, pos.getPage(), this, pos.isMakeNewPage()); PDPageTree pages = origDoc.getDocumentCatalog().getPages(); PDPage page = null; if (pos.isMakeNewPage()) { page = (PDPage) pages.get(pages.getCount() - 1); } else { page = (PDPage) pages.get(pos.getPage() - 1); } logger.debug("PAGE width {} HEIGHT {}", designer.getPageWidth(), designer.getPageHeight()); logger.debug("POS X {} Y {}", pos.getX(), pos.getY()); int rot = page.getRotation(); float posy = designer.getPageHeight() - pos.getY(); float posx = pos.getX(); /*switch (rot) { case 90: // CW posx = designer.getPageHeight() - pos.getY(); posy = designer.getPageWidth() - main.getWidth(); break; case 180: posy = pos.getY(); posx = designer.getPageWidth() - pos.getX(); break; case 270: // CCW posx = pos.getY(); posy = designer.getPageWidth() - pos.getX(); break; }*/ logger.debug("ROT {}", rot); logger.debug("COORD X {} Y {}", posx, posy); designer.coordinates(posx, posy); float[] form_rect = new float[] { 0, 0, main.getWidth() + 2, main.getHeight() + 2 }; logger.debug("AP Rect: {} {} {} {}", form_rect[0], form_rect[1], form_rect[2], form_rect[3]); designer.formaterRectangleParams(form_rect); //this.setPdVisibleSignature(designer); } catch (Throwable e) { e.printStackTrace(); } }
From source file:com.formkiq.core.service.generator.pdfbox.PdfEditorServiceImpl.java
License:Apache License
/** * Generate {@link Map} {@link COSDictionary} to Page Numbers. * @param doc {@link PDDocument}/*from w w w . j a v a 2 s .co m*/ * @return {@link Map} of {@link COSDictionary} to {@link Integer} * @throws IOException IOException */ private Map<COSDictionary, Integer> getCOSDictionaryToPageNumberMap(final PDDocument doc) throws IOException { Map<COSDictionary, Integer> map = new HashMap<>(); PDPageTree pages = doc.getPages(); for (int i = 0; i < pages.getCount(); i++) { for (PDAnnotation annotation : pages.get(i).getAnnotations()) { COSDictionary annotationObject = annotation.getCOSObject(); map.put(annotationObject, Integer.valueOf(i)); } } return map; }
From source file:com.formkiq.core.service.generator.pdfbox.PdfEditorServiceImpl.java
License:Apache License
@Override public Pair<FormJSON, List<WorkflowOutputFormField>> getOutputFormFields(final String filename, final byte[] data) throws IOException { List<WorkflowOutputFormField> wofields = new ArrayList<>(); PDDocument doc = loadPDF(data);//w w w .j a v a2 s . co m try { Map<COSDictionary, Integer> obMap = getCOSDictionaryToPageNumberMap(doc); Map<Integer, List<PDField>> pdMap = getPDFields(doc, obMap); Map<Integer, List<PdfTextField>> textsMap = getTextMap(doc); PDPageTree pages = doc.getDocumentCatalog().getPages(); FormJSON form = buildFormJSON(doc, textsMap.get(Integer.valueOf(0))); for (int i = 0; i < pages.getCount(); i++) { PDPage page = pages.get(i); Integer pageNum = Integer.valueOf(i); List<PDField> fields = pdMap.getOrDefault(pageNum, emptyList()); List<PdfTextField> texts = getTextForPage(textsMap, pageNum); List<PDRectangle> lineRects = getPageLinePaths(pages.get(i)); Map<PDField, FormJSONField> fieldMap = buildFormSection(form, page, fields, texts, lineRects); List<WorkflowOutputFormField> outfields = createFieldOutputs(form, fields, fieldMap); wofields.addAll(outfields); } return Pair.of(form, wofields); } finally { doc.close(); } }
From source file:com.testautomationguru.utility.PDFUtil.java
License:Apache License
/** * This method extracts all the embedded images of the pdf document *///from w w w . ja va 2 s . c o m private List<String> extractimages(String file, int startPage, int endPage) { logger.info("file : " + file); logger.info("startPage : " + startPage); logger.info("endPage : " + endPage); ArrayList<String> imgNames = new ArrayList<String>(); boolean bImageFound = false; try { this.createImageDestinationDirectory(file); String fileName = this.getFileName(file).replace(".pdf", "_resource"); PDDocument document = PDDocument.load(new File(file)); PDPageTree list = document.getPages(); this.updateStartAndEndPages(file, startPage, endPage); int totalImages = 1; for (int iPage = this.startPage - 1; iPage < this.endPage; iPage++) { logger.info("Page No : " + (iPage + 1)); PDResources pdResources = list.get(iPage).getResources(); for (COSName c : pdResources.getXObjectNames()) { PDXObject o = pdResources.getXObject(c); if (o instanceof org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject) { bImageFound = true; String fname = this.imageDestinationPath + "/" + fileName + "_" + totalImages + ".png"; ImageIO.write(((org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject) o).getImage(), "png", new File(fname)); imgNames.add(fname); totalImages++; } } } document.close(); if (bImageFound) logger.info("Images are saved @ " + this.imageDestinationPath); else logger.info("No images were found in the PDF"); } catch (Exception e) { e.printStackTrace(); } return imgNames; }
From source file:org.mycore.media.MCRMediaPDFParser.java
License:Open Source License
/** * Parse file and store metadata in related Object. * /*from w w w . j a v a 2 s . com*/ * @return MCRMediaObject * can be held any MCRMediaObject * @see MCRMediaObject#clone() */ @SuppressWarnings("unchecked") public synchronized MCRMediaObject parse(File file) throws Exception { if (!file.exists()) throw new IOException("File \"" + file.getName() + "\" doesn't exists!"); MCRPDFObject media = new MCRPDFObject(); LOGGER.info("parse " + file.getName() + "..."); PDDocument pdf = PDDocument.load(file); try { media.fileName = file.getName(); media.fileSize = file.length(); media.folderName = (file.getAbsolutePath()).replace(file.getName(), ""); PDPageTree pages = pdf.getDocumentCatalog().getPages(); media.numPages = pdf.getNumberOfPages(); PDPage page = (PDPage) pages.get(0); PDRectangle rect = page.getMediaBox(); media.width = Math.round(rect.getWidth()); media.height = Math.round(rect.getHeight()); PDDocumentInformation info = pdf.getDocumentInformation(); if (info != null) { media.tags = new MCRMediaTagObject(); media.tags.author = info.getAuthor(); media.tags.creator = info.getCreator(); media.tags.producer = info.getProducer(); media.tags.title = info.getTitle(); media.tags.subject = info.getSubject(); media.tags.keywords = info.getKeywords(); } } catch (Exception e) { LOGGER.error(e.getMessage()); throw new Exception(e.getMessage()); } finally { pdf.close(); } return media; }
From source file:org.pdfmetamodifier.OutlineHelper.java
License:Apache License
private static PDOutlineItem createOutlineItem(final String title, final int pageNumber, final PDPageTree pages) { final PDOutlineItem outlineItem = createOutlineItem(title); final PDPageXYZDestination destination = new PDPageXYZDestination(); destination.setPage(pages.get(pageNumber - 1)); outlineItem.setDestination(destination); return outlineItem; }
From source file:org.pdfmetamodifier.OutlineHelperTest.java
License:Apache License
/** * Test for {@link OutlineHelper#lineListToOutlines(org.apache.pdfbox.pdmodel.PDPageTree, java.util.List)} and * {@link OutlineHelper#outlinesToLineList(org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDDocumentOutline, org.apache.pdfbox.pdmodel.PDPageTree, org.apache.pdfbox.pdmodel.PDDestinationNameTreeNode)}. * /* w ww. j a va2 s .c o m*/ * @throws IOException */ @Test public void lineListToOutlinesAndBack() throws IOException { final List<String> lineList = new ArrayList<>(); lineList.add("Bookmarks"); lineList.add(" Title 1|1"); lineList.add(" Title 1.1|2"); lineList.add(" Title 1.2|3"); lineList.add(""); lineList.add(" Title 2|5"); lineList.add(" Title 2.1|6"); lineList.add(" Title 2.2|7"); lineList.add(""); lineList.add(" Title 3|9"); lineList.add(" Title 3.1|10"); lineList.add(" Title 3.2|11"); lineList.add(""); final List<String> cleanLineList = new ArrayList<>(); for (String line : lineList) { if (!line.isEmpty()) { cleanLineList.add(line); } } final PDPageTree pageTree = mock(PDPageTree.class); final List<PDPage> mockPages = new ArrayList<>(); when(pageTree.get(anyInt())).then(new Answer<PDPage>() { @Override public PDPage answer(final InvocationOnMock invocation) throws Throwable { final int idx = (int) invocation.getArguments()[0]; for (int i = mockPages.size(); i <= idx; ++i) { mockPages.add(new PDPage()); } return mockPages.get(idx); } }); when(pageTree.indexOf(any(PDPage.class))).then(new Answer<Integer>() { @Override public Integer answer(final InvocationOnMock invocation) throws Throwable { final PDPage page = (PDPage) invocation.getArguments()[0]; return mockPages.indexOf(page); } }); final PDDocumentOutline documentOutline = OutlineHelper.lineListToOutlines(pageTree, lineList); final List<String> resultLineList = OutlineHelper.outlinesToLineList(documentOutline, pageTree, null); assertEquals(cleanLineList.size(), resultLineList.size()); for (int i = 0; i < cleanLineList.size(); ++i) { assertEquals(cleanLineList.get(i), resultLineList.get(i)); } }
From source file:org.saiku.web.rest.resources.ExporterResource.java
License:Apache License
/** * Export chart to a file.//from w ww . ja va 2s .c o m * @summary Export Chart. * @param type The export type (png, svg, jpeg) * @param svg The SVG * @param size The size * @param name The name * @return A reponse containing the chart export. */ @POST @Produces({ "image/*" }) @Path("/saiku/chart") public Response exportChart(@FormParam("type") @DefaultValue("png") String type, @FormParam("svg") String svg, @FormParam("size") Integer size, @FormParam("name") String name) { try { final String imageType = type.toUpperCase(); Converter converter = Converter.byType("PDF"); if (converter == null) { throw new Exception("Image convert is null"); } // resp.setContentType(converter.getContentType()); // resp.setHeader("Content-disposition", "attachment; filename=chart." + converter.getExtension()); // final Integer size = req.getParameter("size") != null? Integer.parseInt(req.getParameter("size")) : null; // final String svgDocument = req.getParameter("svg"); // if (svgDocument == null) // { // resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing 'svg' parameter"); // return; // } if (StringUtils.isBlank(svg)) { throw new Exception("Missing 'svg' parameter"); } final InputStream in = new ByteArrayInputStream(svg.getBytes("UTF-8")); final ByteArrayOutputStream out = new ByteArrayOutputStream(); converter.convert(in, out, size); out.flush(); byte[] doc = out.toByteArray(); byte[] b = null; if (getVersion() != null && !getVersion().contains("EE")) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfReader reader = new PdfReader(doc); PdfStamper pdfStamper = new PdfStamper(reader, baos); URL dir_url = ExporterResource.class.getResource("/org/saiku/web/svg/watermark.png"); Image image = Image.getInstance(dir_url); for (int i = 1; i <= reader.getNumberOfPages(); i++) { PdfContentByte content = pdfStamper.getOverContent(i); image.setAbsolutePosition(450f, 280f); /*image.setAbsolutePosition(reader.getPageSize(1).getWidth() - image.getScaledWidth(), reader.getPageSize (1).getHeight() - image.getScaledHeight());*/ //image.setAlignment(Image.MIDDLE); content.addImage(image); } pdfStamper.close(); b = baos.toByteArray(); } else { b = doc; } if (!type.equals("pdf")) { PDDocument document = PDDocument.load(new ByteArrayInputStream(b), null); PDPageTree pdPages = document.getDocumentCatalog().getPages(); PDPage page = pdPages.get(0); BufferedImage o = new PDFRenderer(document).renderImage(0); ByteArrayOutputStream imgb = new ByteArrayOutputStream(); String ct = ""; String ext = ""; if (type.equals("png")) { ct = "image/png"; ext = "png"; } else if (type.equals("jpg")) { ct = "image/jpg"; ext = "jpg"; } ImageIO.write(o, type, imgb); byte[] outfile = imgb.toByteArray(); if (name == null || name.equals("")) { name = "chart"; } return Response.ok(outfile).type(ct) .header("content-disposition", "attachment; filename = " + name + "." + ext) .header("content-length", outfile.length).build(); } else { if (name == null || name.equals("")) { name = "chart"; } return Response.ok(b).type(converter.getContentType()) .header("content-disposition", "attachment; filename = " + name + "." + converter.getExtension()) .header("content-length", b.length).build(); } } catch (Exception e) { log.error("Error exporting Chart to " + type, e); return Response.serverError().entity(e.getMessage()).status(Status.INTERNAL_SERVER_ERROR).build(); } }