List of usage examples for org.apache.pdfbox.pdmodel PDPage getRotation
public int getRotation()
From source file:at.gv.egiz.pdfas.lib.impl.pdfbox2.placeholder.SignaturePlaceholderExtractor.java
License:EUPL
@Override protected void processOperator(Operator operator, List<COSBase> arguments) throws IOException { String operation = operator.getName(); if (operation.equals("Do")) { COSName objectName = (COSName) arguments.get(0); PDXObject xobject = (PDXObject) getResources().getXObject(objectName); if (xobject instanceof PDImageXObject) { try { PDImageXObject image = (PDImageXObject) xobject; SignaturePlaceholderData data = checkImage(image); if (data != null) { PDPage page = getCurrentPage(); Matrix ctm = getGraphicsState().getCurrentTransformationMatrix(); int pageRotation = page.getRotation(); pageRotation = pageRotation % 360; double rotationInRadians = Math.toRadians(pageRotation);//(page.findRotation() * Math.PI) / 180; AffineTransform rotation = new AffineTransform(); rotation.setToRotation(rotationInRadians); AffineTransform rotationInverse = rotation.createInverse(); Matrix rotationInverseMatrix = new Matrix(); rotationInverseMatrix.setFromAffineTransform(rotationInverse); Matrix rotationMatrix = new Matrix(); rotationMatrix.setFromAffineTransform(rotation); Matrix unrotatedCTM = ctm.multiply(rotationInverseMatrix); float x = unrotatedCTM.getXPosition(); float yPos = unrotatedCTM.getYPosition(); float yScale = unrotatedCTM.getScaleY(); float y = yPos + yScale; float w = unrotatedCTM.getScaleX(); ;/*from w w w . j a va 2 s .co m*/ logger.debug("Page height: {}", page.getCropBox().getHeight()); logger.debug("Page width: {}", page.getCropBox().getWidth()); if (pageRotation == 90) { y = page.getCropBox().getWidth() - (y * (-1)); } else if (pageRotation == 180) { x = page.getCropBox().getWidth() + x; y = page.getCropBox().getHeight() - (y * (-1)); } else if (pageRotation == 270) { x = page.getCropBox().getHeight() + x; } String posString = "p:" + currentPage + ";x:" + x + ";y:" + y + ";w:" + w; logger.debug("Found Placeholder at: {}", posString); try { data.setTablePos(new TablePos(posString)); data.setPlaceholderName(objectName.getName()); placeholders.add(data); } catch (PdfAsException e) { throw new IOException(); } } } catch (NoninvertibleTransformException e) { throw new IOException(e); } } } else { super.processOperator(operator, arguments); } }
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 w w . j av a 2 s. co m * 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.gv.egiz.pdfas.lib.impl.signing.pdfbox2.PADESPDFBOXSigner.java
License:EUPL
public void signPDF(PDFObject genericPdfObject, RequestedSignature requestedSignature, PDFASSignatureInterface genericSigner) throws PdfAsException { //String fisTmpFile = null; PDFAsVisualSignatureProperties properties = null; if (!(genericPdfObject instanceof PDFBOXObject)) { // tODO://w w w . j a va 2 s.com throw new PdfAsException(); } PDFBOXObject pdfObject = (PDFBOXObject) genericPdfObject; if (!(genericSigner instanceof PDFASPDFBOXSignatureInterface)) { // tODO: throw new PdfAsException(); } PDFASPDFBOXSignatureInterface signer = (PDFASPDFBOXSignatureInterface) genericSigner; String pdfaVersion = null; PDDocument doc = null; SignatureOptions options = new SignatureOptions(); COSDocument visualSignatureDocumentGuard = null; try { doc = pdfObject.getDocument(); SignaturePlaceholderData signaturePlaceholderData = PlaceholderFilter .checkPlaceholderSignature(pdfObject.getStatus(), pdfObject.getStatus().getSettings()); TablePos tablePos = null; if (signaturePlaceholderData != null) { // Placeholder found! logger.info("Placeholder data found."); if (signaturePlaceholderData.getProfile() != null) { logger.debug("Placeholder Profile set to: " + signaturePlaceholderData.getProfile()); requestedSignature.setSignatureProfileID(signaturePlaceholderData.getProfile()); } tablePos = signaturePlaceholderData.getTablePos(); if (tablePos != null) { SignatureProfileConfiguration signatureProfileConfiguration = pdfObject.getStatus() .getSignatureProfileConfiguration(requestedSignature.getSignatureProfileID()); float minWidth = signatureProfileConfiguration.getMinWidth(); if (minWidth > 0) { if (tablePos.getWidth() < minWidth) { tablePos.width = minWidth; logger.debug("Correcting placeholder with to minimum width {}", minWidth); } } logger.debug("Placeholder Position set to: " + tablePos.toString()); } } PDSignature signature = new PDSignature(); signature.setFilter(COSName.getPDFName(signer.getPDFFilter())); // default // filter signature.setSubFilter(COSName.getPDFName(signer.getPDFSubFilter())); SignatureProfileSettings signatureProfileSettings = TableFactory .createProfile(requestedSignature.getSignatureProfileID(), pdfObject.getStatus().getSettings()); /* * Check if input document is PDF-A conform * if (signatureProfileSettings.isPDFA()) { // TODO: run preflight parser runPDFAPreflight(pdfObject.getOriginalDocument()); } */ ValueResolver resolver = new ValueResolver(requestedSignature, pdfObject.getStatus()); String signerName = resolver.resolve("SIG_SUBJECT", signatureProfileSettings.getValue("SIG_SUBJECT"), signatureProfileSettings); signature.setName(signerName); // take signing time from provided signer... signature.setSignDate(signer.getSigningDate()); // ...and update operation status in order to use exactly this date for the complete signing process requestedSignature.getStatus().setSigningDate(signer.getSigningDate()); String signerReason = signatureProfileSettings.getSigningReason(); if (signerReason == null) { signerReason = "PAdES Signature"; } signature.setReason(signerReason); logger.debug("Signing reason: " + signerReason); logger.debug("Signing @ " + signer.getSigningDate().getTime().toString()); // the signing date, needed for valid signature // signature.setSignDate(signer.getSigningDate()); signer.setPDSignature(signature); int signatureSize = 0x1000; try { String reservedSignatureSizeString = signatureProfileSettings.getValue(SIG_RESERVED_SIZE); if (reservedSignatureSizeString != null) { signatureSize = Integer.parseInt(reservedSignatureSizeString); } logger.debug("Reserving {} bytes for signature", signatureSize); } catch (NumberFormatException e) { logger.warn("Invalid configuration value: {} should be a number using 0x1000", SIG_RESERVED_SIZE); } options.setPreferredSignatureSize(signatureSize); if (signatureProfileSettings.isPDFA() || signatureProfileSettings.isPDFA3()) { pdfaVersion = getPDFAVersion(doc); signatureProfileSettings.setPDFAVersion(pdfaVersion); } // Is visible Signature if (requestedSignature.isVisual()) { logger.debug("Creating visual signature block"); SignatureProfileConfiguration signatureProfileConfiguration = pdfObject.getStatus() .getSignatureProfileConfiguration(requestedSignature.getSignatureProfileID()); if (tablePos == null) { // ================================================================ // PositioningStage (visual) -> find position or use // fixed // position String posString = pdfObject.getStatus().getSignParamter().getSignaturePosition(); TablePos signaturePos = null; String signaturePosString = signatureProfileConfiguration.getDefaultPositioning(); if (signaturePosString != null) { logger.debug("using signature Positioning: " + signaturePos); signaturePos = new TablePos(signaturePosString); } logger.debug("using Positioning: " + posString); if (posString != null) { // Merge Signature Position tablePos = new TablePos(posString, signaturePos); } else { // Fallback to signature Position! tablePos = signaturePos; } if (tablePos == null) { // Last Fallback default position tablePos = new TablePos(); } } //Legacy Modes not supported with pdfbox2 anymore // boolean legacy32Position = signatureProfileConfiguration.getLegacy32Positioning(); // boolean legacy40Position = signatureProfileConfiguration.getLegacy40Positioning(); // create Table describtion Table main = TableFactory.createSigTable(signatureProfileSettings, MAIN, pdfObject.getStatus(), requestedSignature); IPDFStamper stamper = StamperFactory.createDefaultStamper(pdfObject.getStatus().getSettings()); IPDFVisualObject visualObject = stamper.createVisualPDFObject(pdfObject, main); /* * PDDocument originalDocument = PDDocument .load(new * ByteArrayInputStream(pdfObject.getStatus() * .getPdfObject().getOriginalDocument())); */ PositioningInstruction positioningInstruction = Positioning.determineTablePositioning(tablePos, "", doc, visualObject, pdfObject.getStatus().getSettings()); logger.debug("Positioning: {}", positioningInstruction.toString()); if (positioningInstruction.isMakeNewPage()) { int last = doc.getNumberOfPages() - 1; PDDocumentCatalog root = doc.getDocumentCatalog(); PDPage lastPage = root.getPages().get(last); root.getPages().getCOSObject().setNeedToBeUpdated(true); PDPage p = new PDPage(lastPage.getMediaBox()); p.setResources(new PDResources()); p.setRotation(lastPage.getRotation()); doc.addPage(p); } // handle rotated page int targetPageNumber = positioningInstruction.getPage(); logger.debug("Target Page: " + targetPageNumber); PDPage targetPage = doc.getPages().get(targetPageNumber - 1); int rot = targetPage.getRotation(); logger.debug("Page rotation: " + rot); // positioningInstruction.setRotation(positioningInstruction.getRotation() // + rot); logger.debug("resulting Sign rotation: " + positioningInstruction.getRotation()); SignaturePositionImpl position = new SignaturePositionImpl(); position.setX(positioningInstruction.getX()); position.setY(positioningInstruction.getY()); position.setPage(positioningInstruction.getPage()); position.setHeight(visualObject.getHeight()); position.setWidth(visualObject.getWidth()); requestedSignature.setSignaturePosition(position); properties = new PDFAsVisualSignatureProperties(pdfObject.getStatus().getSettings(), pdfObject, (PdfBoxVisualObject) visualObject, positioningInstruction, signatureProfileSettings); properties.buildSignature(); /* * ByteArrayOutputStream sigbos = new * ByteArrayOutputStream(); * sigbos.write(StreamUtils.inputStreamToByteArray * (properties .getVisibleSignature())); sigbos.close(); */ if (signaturePlaceholderData != null) { // Placeholder found! // replace placeholder URL fileUrl = PADESPDFBOXSigner.class.getResource("/placeholder/empty.jpg"); PDImageXObject img = PDImageXObject.createFromFile(fileUrl.getPath(), doc); img.getCOSObject().setNeedToBeUpdated(true); // PDDocumentCatalog root = doc.getDocumentCatalog(); // PDPageNode rootPages = root.getPages(); // List<PDPage> kids = new ArrayList<PDPage>(); // rootPages.getAllKids(kids); int pageNumber = positioningInstruction.getPage(); PDPage page = doc.getPages().get(pageNumber - 1); logger.info("Placeholder name: " + signaturePlaceholderData.getPlaceholderName()); COSDictionary xobjectsDictionary = (COSDictionary) page.getResources().getCOSObject() .getDictionaryObject(COSName.XOBJECT); xobjectsDictionary.setItem(signaturePlaceholderData.getPlaceholderName(), img); xobjectsDictionary.setNeedToBeUpdated(true); page.getResources().getCOSObject().setNeedToBeUpdated(true); logger.info("Placeholder name: " + signaturePlaceholderData.getPlaceholderName()); } if (signatureProfileSettings.isPDFA() || signatureProfileSettings.isPDFA3()) { PDDocumentCatalog root = doc.getDocumentCatalog(); COSBase base = root.getCOSObject().getItem(COSName.OUTPUT_INTENTS); if (base == null) { InputStream colorProfile = null; try { colorProfile = PDDocumentCatalog.class .getResourceAsStream("/icm/sRGB Color Space Profile.icm"); try { PDOutputIntent oi = new PDOutputIntent(doc, colorProfile); oi.setInfo("sRGB IEC61966-2.1"); oi.setOutputCondition("sRGB IEC61966-2.1"); oi.setOutputConditionIdentifier("sRGB IEC61966-2.1"); oi.setRegistryName("http://www.color.org"); root.addOutputIntent(oi); root.getCOSObject().setNeedToBeUpdated(true); logger.info("added Output Intent"); } catch (Throwable e) { e.printStackTrace(); throw new PdfAsException("Failed to add Output Intent", e); } } finally { IOUtils.closeQuietly(colorProfile); } } } options.setPage(positioningInstruction.getPage()); options.setVisualSignature(properties.getVisibleSignature()); } visualSignatureDocumentGuard = options.getVisualSignature(); doc.addSignature(signature, signer, options); String sigFieldName = signatureProfileSettings.getSignFieldValue(); if (sigFieldName == null) { sigFieldName = "PDF-AS Signatur"; } int count = PdfBoxUtils.countSignatures(doc, sigFieldName); sigFieldName = sigFieldName + count; PDAcroForm acroFormm = doc.getDocumentCatalog().getAcroForm(); // PDStructureTreeRoot pdstRoot = // doc.getDocumentCatalog().getStructureTreeRoot(); // COSDictionary dic = // doc.getDocumentCatalog().getCOSDictionary(); // PDStructureElement el = new PDStructureElement("Widget", // pdstRoot); PDSignatureField signatureField = null; if (acroFormm != null) { @SuppressWarnings("unchecked") List<PDField> fields = acroFormm.getFields(); if (fields != null) { for (PDField pdField : fields) { if (pdField != null) { if (pdField instanceof PDSignatureField) { PDSignatureField tmpSigField = (PDSignatureField) pdField; if (tmpSigField.getSignature() != null && tmpSigField.getSignature().getCOSObject() != null) { if (tmpSigField.getSignature().getCOSObject() .equals(signature.getCOSObject())) { signatureField = (PDSignatureField) pdField; } } } } } } else { logger.warn("Failed to name Signature Field! [Cannot find Field list in acroForm!]"); } if (signatureField != null) { signatureField.setPartialName(sigFieldName); } if (properties != null) { signatureField.setAlternateFieldName(properties.getAlternativeTableCaption()); } else { signatureField.setAlternateFieldName(sigFieldName); } } else { logger.warn("Failed to name Signature Field! [Cannot find acroForm!]"); } // PDF-UA logger.info("Adding pdf/ua content."); try { PDDocumentCatalog root = doc.getDocumentCatalog(); PDStructureTreeRoot structureTreeRoot = root.getStructureTreeRoot(); if (structureTreeRoot != null) { logger.info("Tree Root: {}", structureTreeRoot.toString()); List<Object> kids = structureTreeRoot.getKids(); if (kids == null) { logger.info("No kid-elements in structure tree Root, maybe not PDF/UA document"); } PDStructureElement docElement = null; for (Object k : kids) { if (k instanceof PDStructureElement) { docElement = (PDStructureElement) k; break; } } PDStructureElement sigBlock = new PDStructureElement("Form", docElement); // create object dictionary and add as child element COSDictionary objectDic = new COSDictionary(); objectDic.setName("Type", "OBJR"); objectDic.setItem("Pg", signatureField.getWidget().getPage()); objectDic.setItem("Obj", signatureField.getWidget()); List<Object> l = new ArrayList<Object>(); l.add(objectDic); sigBlock.setKids(l); sigBlock.setPage(signatureField.getWidget().getPage()); sigBlock.setTitle("Signature Table"); sigBlock.setParent(docElement); docElement.appendKid(sigBlock); // Create and add Attribute dictionary to mitigate PAC // warning COSDictionary sigBlockDic = (COSDictionary) sigBlock.getCOSObject(); COSDictionary sub = new COSDictionary(); sub.setName("O", "Layout"); sub.setName("Placement", "Block"); sigBlockDic.setItem(COSName.A, sub); sigBlockDic.setNeedToBeUpdated(true); // Modify number tree PDNumberTreeNode ntn = structureTreeRoot.getParentTree(); int parentTreeNextKey = structureTreeRoot.getParentTreeNextKey(); if (ntn == null) { ntn = new PDNumberTreeNode(objectDic, null); logger.info("No number-tree-node found!"); } COSArray ntnKids = (COSArray) ntn.getCOSObject().getDictionaryObject(COSName.KIDS); COSArray ntnNumbers = (COSArray) ntn.getCOSObject().getDictionaryObject(COSName.NUMS); if (ntnNumbers == null && ntnKids != null) {//no number array, so continue with the kids array //create dictionary with limits and nums array COSDictionary pTreeEntry = new COSDictionary(); COSArray limitsArray = new COSArray(); //limits for exact one entry limitsArray.add(COSInteger.get(parentTreeNextKey)); limitsArray.add(COSInteger.get(parentTreeNextKey)); COSArray numsArray = new COSArray(); numsArray.add(COSInteger.get(parentTreeNextKey)); numsArray.add(sigBlock); pTreeEntry.setItem(COSName.NUMS, numsArray); pTreeEntry.setItem(COSName.LIMITS, limitsArray); PDNumberTreeNode newKidsElement = new PDNumberTreeNode(pTreeEntry, PDNumberTreeNode.class); ntnKids.add(newKidsElement); ntnKids.setNeedToBeUpdated(true); } else if (ntnNumbers != null && ntnKids == null) { int arrindex = ntnNumbers.size(); ntnNumbers.add(arrindex, COSInteger.get(parentTreeNextKey)); ntnNumbers.add(arrindex + 1, sigBlock.getCOSObject()); ntnNumbers.setNeedToBeUpdated(true); structureTreeRoot.setParentTree(ntn); } else if (ntnNumbers == null && ntnKids == null) { //document is not pdfua conform before signature creation throw new PdfAsException("error.pdf.sig.pdfua.1"); } else { //this is not allowed throw new PdfAsException("error.pdf.sig.pdfua.1"); } // set StructureParent for signature field annotation signatureField.getWidget().setStructParent(parentTreeNextKey); //Increase the next Key value in the structure tree root structureTreeRoot.setParentTreeNextKey(parentTreeNextKey + 1); // add the Tabs /S Element for Tabbing through annots PDPage p = signatureField.getWidget().getPage(); p.getCOSObject().setName("Tabs", "S"); p.getCOSObject().setNeedToBeUpdated(true); //check alternative signature field name if (signatureField != null) { if (signatureField.getAlternateFieldName().equals("")) signatureField.setAlternateFieldName(sigFieldName); } ntn.getCOSObject().setNeedToBeUpdated(true); sigBlock.getCOSObject().setNeedToBeUpdated(true); structureTreeRoot.getCOSObject().setNeedToBeUpdated(true); objectDic.setNeedToBeUpdated(true); docElement.getCOSObject().setNeedToBeUpdated(true); } } catch (Throwable e) { if (signatureProfileSettings.isPDFUA() == true) { logger.error("Could not create PDF-UA conform document!"); throw new PdfAsException("error.pdf.sig.pdfua.1", e); } else { logger.info("Could not create PDF-UA conform signature"); } } try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); synchronized (doc) { doc.saveIncremental(bos); byte[] outputDocument = bos.toByteArray(); /* Check if resulting pdf is PDF-A conform */ //if (signatureProfileSettings.isPDFA()) { // // TODO: run preflight parser // runPDFAPreflight(outputDocument); //} pdfObject.setSignedDocument(outputDocument); } } finally { if (options != null) { if (options.getVisualSignature() != null) { options.getVisualSignature().close(); } } } System.gc(); } catch (IOException e) { logger.warn(MessageResolver.resolveMessage("error.pdf.sig.01"), e); throw new PdfAsException("error.pdf.sig.01", e); } finally { if (doc != null) { try { doc.close(); } catch (IOException e) { logger.debug("Failed to close COS Doc!", e); // Ignore } } logger.debug("Signature done!"); } }
From source file:at.gv.egiz.pdfas.lib.impl.stamping.pdfbox2.PDFAsVisualSignatureDesigner.java
License:EUPL
/** * Each page of document can be different sizes. * /*ww w.j a va 2s . c om*/ * @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.PDFAsVisualSignatureProperties.java
License:EUPL
public PDFAsVisualSignatureProperties(ISettings settings, PDFBOXObject object, PdfBoxVisualObject visObj, PositioningInstruction pos, SignatureProfileSettings signatureProfileSettings) { this.settings = settings; this.signatureProfileSettings = signatureProfileSettings; try {//from w w w.ja va2 s . c om 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:at.knowcenter.wag.egov.egiz.pdfbox2.pdf.PDFPage.java
License:EUPL
public void processAnnotation(PDAnnotation anno) { float current_y = anno.getRectangle().getLowerLeftY(); float upper_y = 0; PDPage page = anno.getPage(); if (page == null) { page = getCurrentPage();/* ww w . j av a2s .c o m*/ } if (page == null) { logger.warn("Annotation without page! The position might not be correct!"); return; } int pageRotation = page.getRotation(); // logger_.debug("PageRotation = " + pageRotation); if (pageRotation == 0) { float page_height = page.getMediaBox().getHeight(); current_y = page_height - anno.getRectangle().getLowerLeftY(); upper_y = page_height - anno.getRectangle().getUpperRightY(); } if (pageRotation == 90) { current_y = anno.getRectangle().getUpperRightX(); upper_y = anno.getRectangle().getLowerLeftX(); } if (pageRotation == 180) { current_y = anno.getRectangle().getUpperRightY(); upper_y = anno.getRectangle().getLowerLeftY(); } if (pageRotation == 270) { float page_width = page.getMediaBox().getWidth(); current_y = page_width - anno.getRectangle().getLowerLeftX(); upper_y = page_width - anno.getRectangle().getUpperRightX(); } if (current_y > this.effectivePageHeight) { if (!this.legacy40 && upper_y < this.effectivePageHeight) { // Bottom of annotation is below footer line, // but top of annotation is above footer line! // so no place left on this page! this.max_character_ypos = this.effectivePageHeight; } return; } // store ypos of the char if it is not empty if (current_y > this.max_character_ypos) { this.max_character_ypos = current_y; } }
From source file:ch.rasc.downloadchart.DownloadChartServlet.java
License:Apache License
private static void handlePdf(HttpServletResponse response, byte[] imageData, Integer width, Integer height, String filename, PdfOptions options) throws IOException { response.setContentType("application/pdf"); response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + ".pdf\";"); try (PDDocument document = new PDDocument()) { PDRectangle format = PDPage.PAGE_SIZE_A4; if (options != null) { if ("A3".equals(options.format)) { format = PDPage.PAGE_SIZE_A3; } else if ("A5".equals(options.format)) { format = PDPage.PAGE_SIZE_A5; } else if ("Letter".equals(options.format)) { format = PDPage.PAGE_SIZE_LETTER; } else if ("Legal".equals(options.format)) { format = new PDRectangle(215.9f * MM_TO_UNITS, 355.6f * MM_TO_UNITS); } else if ("Tabloid".equals(options.format)) { format = new PDRectangle(279 * MM_TO_UNITS, 432 * MM_TO_UNITS); } else if (options.width != null && options.height != null) { Float pdfWidth = convertToPixel(options.width); Float pdfHeight = convertToPixel(options.height); if (pdfWidth != null && pdfHeight != null) { format = new PDRectangle(pdfWidth, pdfHeight); }/*from ww w . j av a2 s . c o m*/ } } PDPage page = new PDPage(format); if (options != null && "landscape".equals(options.orientation)) { page.setRotation(90); } document.addPage(page); BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(imageData)); try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) { PDPixelMap ximage = new PDPixelMap(document, originalImage); Dimension newDimension = calculateDimension(originalImage, width, height); int imgWidth = ximage.getWidth(); int imgHeight = ximage.getHeight(); if (newDimension != null) { imgWidth = newDimension.width; imgHeight = newDimension.height; } Float border = options != null ? convertToPixel(options.border) : null; if (border == null) { border = 0.0f; } AffineTransform transform; if (page.getRotation() == null) { float scale = (page.getMediaBox().getWidth() - border * 2) / imgWidth; if (scale < 1.0) { transform = new AffineTransform(imgWidth, 0, 0, imgHeight, border, page.getMediaBox().getHeight() - border - imgHeight * scale); transform.scale(scale, scale); } else { transform = new AffineTransform(imgWidth, 0, 0, imgHeight, border, page.getMediaBox().getHeight() - border - imgHeight); } } else { float scale = (page.getMediaBox().getHeight() - border * 2) / imgWidth; if (scale < 1.0) { transform = new AffineTransform(imgHeight, 0, 0, imgWidth, imgHeight * scale + border, border); transform.scale(scale, scale); } else { transform = new AffineTransform(imgHeight, 0, 0, imgWidth, imgHeight + border, border); } transform.rotate(1.0 * Math.PI / 2.0); } contentStream.drawXObject(ximage, transform); } try { document.save(response.getOutputStream()); } catch (COSVisitorException e) { throw new IOException(e); } } }
From source file:com.devnexus.ting.web.controller.PdfUtils.java
License:Apache License
boolean isLandscape(PDPage page) { int rotation = page.getRotation(); final boolean isLandscape; if (rotation == 90 || rotation == 270) { isLandscape = true;// w ww . j a v a 2 s. com } else if (rotation == 0 || rotation == 360 || rotation == 180) { isLandscape = false; } else { LOGGER.warn( "Can only handle pages that are rotated in 90 degree steps. This page is rotated {} degrees. Will treat the page as in portrait format", rotation); isLandscape = false; } return isLandscape; }
From source file:com.repeatability.pdf.PDFTextStreamEngine.java
License:Apache License
/** * This will initialise and process the contents of the stream. * * @param page the page to process//from www. j ava 2s . co m * @throws java.io.IOException if there is an error accessing the stream. */ @Override public void processPage(PDPage page) throws IOException { this.pageRotation = page.getRotation(); this.pageSize = page.getCropBox(); if (pageSize.getLowerLeftX() == 0 && pageSize.getLowerLeftY() == 0) { translateMatrix = null; } else { // translation matrix for cropbox translateMatrix = Matrix.getTranslateInstance(-pageSize.getLowerLeftX(), -pageSize.getLowerLeftY()); } super.processPage(page); }
From source file:com.trollworks.gcs.pdfview.PdfRenderer.java
License:Open Source License
@Override protected void writeString(String text, List<TextPosition> textPositions) throws IOException { text = text.toLowerCase();//from ww w .ja v a2s . com int index = text.indexOf(mTextToHighlight); if (index != -1) { PDPage currentPage = getCurrentPage(); PDRectangle pageBoundingBox = currentPage.getBBox(); AffineTransform flip = new AffineTransform(); flip.translate(0, pageBoundingBox.getHeight()); flip.scale(1, -1); PDRectangle mediaBox = currentPage.getMediaBox(); float mediaHeight = mediaBox.getHeight(); float mediaWidth = mediaBox.getWidth(); int size = textPositions.size(); while (index != -1) { int last = index + mTextToHighlight.length() - 1; for (int i = index; i <= last; i++) { TextPosition pos = textPositions.get(i); PDFont font = pos.getFont(); BoundingBox bbox = font.getBoundingBox(); Rectangle2D.Float rect = new Rectangle2D.Float(0, bbox.getLowerLeftY(), font.getWidth(pos.getCharacterCodes()[0]), bbox.getHeight()); AffineTransform at = pos.getTextMatrix().createAffineTransform(); if (font instanceof PDType3Font) { at.concatenate(font.getFontMatrix().createAffineTransform()); } else { at.scale(1 / 1000f, 1 / 1000f); } Shape shape = flip.createTransformedShape(at.createTransformedShape(rect)); AffineTransform transform = mGC.getTransform(); int rotation = currentPage.getRotation(); if (rotation != 0) { switch (rotation) { case 90: mGC.translate(mediaHeight, 0); break; case 270: mGC.translate(0, mediaWidth); break; case 180: mGC.translate(mediaWidth, mediaHeight); break; default: break; } mGC.rotate(Math.toRadians(rotation)); } mGC.fill(shape); if (rotation != 0) { mGC.setTransform(transform); } } index = last < size - 1 ? text.indexOf(mTextToHighlight, last + 1) : -1; } } }