List of usage examples for org.apache.pdfbox.pdmodel PDPage setRotation
public void setRotation(int rotation)
From source file:at.gv.egiz.pdfas.lib.impl.signing.pdfbox.PADESPDFBOXSigner.java
License:EUPL
public void signPDF(PDFObject genericPdfObject, RequestedSignature requestedSignature, PDFASSignatureInterface genericSigner) throws PdfAsException { String fisTmpFile = null;//from ww w .j ava 2s. c o m PDFAsVisualSignatureProperties properties = null; if (!(genericPdfObject instanceof PDFBOXObject)) { // tODO: throw new PdfAsException(); } PDFBOXObject pdfObject = (PDFBOXObject) genericPdfObject; if (!(genericSigner instanceof PDFASPDFBOXSignatureInterface)) { // tODO: throw new PdfAsException(); } PDFASPDFBOXSignatureInterface signer = (PDFASPDFBOXSignatureInterface) genericSigner; TempFileHelper helper = pdfObject.getStatus().getTempFileHelper(); PDDocument doc = pdfObject.getDocument(); SignatureOptions options = new SignatureOptions(); COSDocument visualSignatureDocumentGuard = null; try { fisTmpFile = helper.getStaticFilename(); FileOutputStream tmpOutputStream = null; try { // write to temporary file tmpOutputStream = new FileOutputStream(new File(fisTmpFile)); InputStream tmpis = null; try { tmpis = pdfObject.getOriginalDocument().getInputStream(); IOUtils.copy(tmpis, tmpOutputStream); tmpis.close(); } finally { IOUtils.closeQuietly(tmpis); } 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()); 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.setPreferedSignatureSize(signatureSize); // 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(); } } 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, legacy32Position, legacy40Position); logger.debug("Positioning: {}", positioningInstruction.toString()); if (positioningInstruction.isMakeNewPage()) { int last = doc.getNumberOfPages() - 1; PDDocumentCatalog root = doc.getDocumentCatalog(); PDPageNode rootPages = root.getPages(); List<PDPage> kids = new ArrayList<PDPage>(); rootPages.getAllKids(kids); PDPage lastPage = kids.get(last); rootPages.getCOSObject().setNeedToBeUpdate(true); PDPage p = new PDPage(lastPage.findMediaBox()); p.setResources(new PDResources()); p.setRotation(lastPage.findRotation()); doc.addPage(p); } // handle rotated page PDDocumentCatalog documentCatalog = doc.getDocumentCatalog(); PDPageNode documentPages = documentCatalog.getPages(); List<PDPage> documentPagesKids = new ArrayList<PDPage>(); documentPages.getAllKids(documentPagesKids); int targetPageNumber = positioningInstruction.getPage(); logger.debug("Target Page: " + targetPageNumber); // rootPages.getAllKids(kids); PDPage targetPage = documentPagesKids.get(targetPageNumber - 1); int rot = targetPage.findRotation(); 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 InputStream is = null; try { is = PADESPDFBOXSigner.class.getResourceAsStream("/placeholder/empty.jpg"); PDJpeg img = new PDJpeg(doc, is); img.getCOSObject().setNeedToBeUpdate(true); PDDocumentCatalog root = doc.getDocumentCatalog(); PDPageNode rootPages = root.getPages(); List<PDPage> kids = new ArrayList<PDPage>(); rootPages.getAllKids(kids); int pageNumber = positioningInstruction.getPage(); // rootPages.getAllKids(kids); PDPage page = kids.get(pageNumber - 1); logger.info("Placeholder name: " + signaturePlaceholderData.getPlaceholderName()); COSDictionary xobjectsDictionary = (COSDictionary) page.findResources() .getCOSDictionary().getDictionaryObject(COSName.XOBJECT); xobjectsDictionary.setItem(signaturePlaceholderData.getPlaceholderName(), img); xobjectsDictionary.setNeedToBeUpdate(true); page.findResources().getCOSObject().setNeedToBeUpdate(true); logger.info("Placeholder name: " + signaturePlaceholderData.getPlaceholderName()); } finally { IOUtils.closeQuietly(is); } } if (signatureProfileSettings.isPDFA()) { PDDocumentCatalog root = doc.getDocumentCatalog(); COSBase base = root.getCOSDictionary().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().setNeedToBeUpdate(true); logger.info("added Output Intent"); } catch (Throwable e) { 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); // set need to update indirect fields array in acro form COSDictionary trailer = doc.getDocument().getTrailer(); if (trailer != null) { COSDictionary troot = (COSDictionary) trailer.getDictionaryObject(COSName.ROOT); if (troot != null) { COSDictionary acroForm = (COSDictionary) troot.getDictionaryObject(COSName.ACRO_FORM); if (acroForm != null) { COSArray tfields = (COSArray) acroForm.getDictionaryObject(COSName.FIELDS); if (tfields != null && !tfields.isDirect()) { tfields.setNeedToBeUpdate(true); } } } } 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(); 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().getDictionary() != null) { if (tmpSigField.getSignature().getDictionary() .equals(signature.getDictionary())) { 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.setNeedToBeUpdate(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.getCOSDictionary().getDictionaryObject(COSName.KIDS); COSArray ntnNumbers = (COSArray) ntn.getCOSDictionary().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.setNeedToBeUpdate(true); //working // List<PDNumberTreeNode> treeRootKids = structureTreeRoot.getParentTree().getKids(); // PDNumberTreeNode last = (PDNumberTreeNode)treeRootKids.get(treeRootKids.size()-1); // COSArray lim1 = (COSArray) last.getCOSDictionary().getDictionaryObject(COSName.LIMITS); // lim1.remove(1); // lim1.add(1, COSInteger.get(parentTreeNextKey)); // PDNumberTreeNode verylast = (PDNumberTreeNode)last.getKids().get(last.getKids().size()-1); // COSArray numa = (COSArray) verylast.getCOSDictionary().getDictionaryObject(COSName.NUMS); // COSArray lim = (COSArray) verylast.getCOSDictionary().getDictionaryObject(COSName.LIMITS); // lim.remove(1); // lim.add(1, COSInteger.get(parentTreeNextKey)); // // int size = numa.size(); // numa.add(size, COSInteger.get(parentTreeNextKey)); // numa.add(sigBlock); //working end } else if (ntnNumbers != null && ntnKids == null) { int arrindex = ntnNumbers.size(); ntnNumbers.add(arrindex, COSInteger.get(parentTreeNextKey)); ntnNumbers.add(arrindex + 1, sigBlock.getCOSObject()); ntnNumbers.getCOSObject().setNeedToBeUpdate(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.getCOSDictionary().setName("Tabs", "S"); p.getCOSObject().setNeedToBeUpdate(true); //check alternative signature field name if (signatureField != null) { if (signatureField.getAlternateFieldName().equals("")) signatureField.setAlternateFieldName(sigFieldName); } ntn.getCOSDictionary().setNeedToBeUpdate(true); sigBlock.getCOSObject().setNeedToBeUpdate(true); structureTreeRoot.getCOSObject().setNeedToBeUpdate(true); objectDic.getCOSObject().setNeedToBeUpdate(true); docElement.getCOSObject().setNeedToBeUpdate(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 { applyFilter(doc, requestedSignature); } catch (PDFASError e) { throw new PdfAsErrorCarrier(e); } FileInputStream tmpFileIs = null; try { tmpFileIs = new FileInputStream(new File(fisTmpFile)); synchronized (doc) { doc.saveIncremental(tmpFileIs, tmpOutputStream); } tmpFileIs.close(); } finally { IOUtils.closeQuietly(tmpFileIs); if (options != null) { if (options.getVisualSignature() != null) { options.getVisualSignature().close(); } } } tmpOutputStream.flush(); tmpOutputStream.close(); } finally { IOUtils.closeQuietly(tmpOutputStream); COSDocument visualSignature = options.getVisualSignature(); if (visualSignature != null) { visualSignature.close(); } } FileInputStream readReadyFile = null; try { readReadyFile = new FileInputStream(new File(fisTmpFile)); // write to resulting output stream // ByteArrayOutputStream bos = new ByteArrayOutputStream(); // bos.write(); // bos.close(); pdfObject.setSignedDocument(StreamUtils.inputStreamToByteArray(readReadyFile)); readReadyFile.close(); } finally { IOUtils.closeQuietly(readReadyFile); } } catch (IOException e) { logger.info(MessageResolver.resolveMessage("error.pdf.sig.01") + ": {}", e.toString()); throw new PdfAsException("error.pdf.sig.01", e); } catch (SignatureException e) { logger.info(MessageResolver.resolveMessage("error.pdf.sig.01") + ": {}", e.toString()); throw new PdfAsException("error.pdf.sig.01", e); } catch (COSVisitorException e) { logger.info(MessageResolver.resolveMessage("error.pdf.sig.01") + ": {}", e.toString()); 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 } } if (fisTmpFile != null) { helper.deleteFile(fisTmpFile); } logger.debug("Signature done!"); } }
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://from www .j a va 2 s . co m 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.pdfbox.PDFAsVisualSignatureBuilder.java
License:EUPL
public void createPage(PDFAsVisualSignatureDesigner properties) { PDPage page = new PDPage(); page.setMediaBox(new PDRectangle(properties.getPageWidth(), properties.getPageHeight())); page.setRotation(properties.getPageRotation()); getStructure().setPage(page);//from w w w . ja va 2 s . co m logger.debug("PDF page has been created"); }
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 w w w . j a va 2 s. co 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.fangxin365.core.utils.PDFMerger.java
License:Apache License
/** * append all pages from source to destination. * /*from w w w. j a va 2 s. c o m*/ * @param destination * the document to receive the pages * @param source * the document originating the new pages * * @throws IOException * If there is an error accessing data from either document. */ public void appendDocument(PDDocument destination, PDDocument source) throws IOException { if (destination.isEncrypted()) { System.out.println("Error: destination PDF is encrypted, can't append encrypted PDF documents."); } if (source.isEncrypted()) { System.out.println("Error: source PDF is encrypted, can't append encrypted PDF documents."); } PDDocumentInformation destInfo = destination.getDocumentInformation(); PDDocumentInformation srcInfo = source.getDocumentInformation(); destInfo.getDictionary().mergeInto(srcInfo.getDictionary()); PDDocumentCatalog destCatalog = destination.getDocumentCatalog(); PDDocumentCatalog srcCatalog = source.getDocumentCatalog(); // use the highest version number for the resulting pdf float destVersion = destination.getDocument().getVersion(); float srcVersion = source.getDocument().getVersion(); if (destVersion < srcVersion) { destination.getDocument().setVersion(srcVersion); } if (destCatalog.getOpenAction() == null) { destCatalog.setOpenAction(srcCatalog.getOpenAction()); } // maybe there are some shared resources for all pages COSDictionary srcPages = (COSDictionary) srcCatalog.getCOSDictionary().getDictionaryObject(COSName.PAGES); COSDictionary srcResources = (COSDictionary) srcPages.getDictionaryObject(COSName.RESOURCES); COSDictionary destPages = (COSDictionary) destCatalog.getCOSDictionary().getDictionaryObject(COSName.PAGES); COSDictionary destResources = (COSDictionary) destPages.getDictionaryObject(COSName.RESOURCES); if (srcResources != null) { if (destResources != null) { destResources.mergeInto(srcResources); } else { destPages.setItem(COSName.RESOURCES, srcResources); } } PDFCloneUtility cloner = new PDFCloneUtility(destination); try { PDAcroForm destAcroForm = destCatalog.getAcroForm(); PDAcroForm srcAcroForm = srcCatalog.getAcroForm(); if (destAcroForm == null) { cloner.cloneForNewDocument(srcAcroForm); destCatalog.setAcroForm(srcAcroForm); } else { if (srcAcroForm != null) { mergeAcroForm(cloner, destAcroForm, srcAcroForm); } } } catch (Exception e) { // if we are not ignoring exceptions, we'll re-throw this if (!ignoreAcroFormErrors) { throw (IOException) e; } } COSArray destThreads = (COSArray) destCatalog.getCOSDictionary().getDictionaryObject(COSName.THREADS); COSArray srcThreads = (COSArray) cloner .cloneForNewDocument(destCatalog.getCOSDictionary().getDictionaryObject(COSName.THREADS)); if (destThreads == null) { destCatalog.getCOSDictionary().setItem(COSName.THREADS, srcThreads); } else { destThreads.addAll(srcThreads); } PDDocumentNameDictionary destNames = destCatalog.getNames(); PDDocumentNameDictionary srcNames = srcCatalog.getNames(); if (srcNames != null) { if (destNames == null) { destCatalog.getCOSDictionary().setItem(COSName.NAMES, cloner.cloneForNewDocument(srcNames)); } else { cloner.cloneMerge(srcNames, destNames); } } PDDocumentOutline destOutline = destCatalog.getDocumentOutline(); PDDocumentOutline srcOutline = srcCatalog.getDocumentOutline(); if (srcOutline != null) { if (destOutline == null) { PDDocumentOutline cloned = new PDDocumentOutline( (COSDictionary) cloner.cloneForNewDocument(srcOutline)); destCatalog.setDocumentOutline(cloned); } else { PDOutlineItem first = srcOutline.getFirstChild(); if (first != null) { PDOutlineItem clonedFirst = new PDOutlineItem( (COSDictionary) cloner.cloneForNewDocument(first)); destOutline.appendChild(clonedFirst); } } } String destPageMode = destCatalog.getPageMode(); String srcPageMode = srcCatalog.getPageMode(); if (destPageMode == null) { destCatalog.setPageMode(srcPageMode); } COSDictionary destLabels = (COSDictionary) destCatalog.getCOSDictionary() .getDictionaryObject(COSName.PAGE_LABELS); COSDictionary srcLabels = (COSDictionary) srcCatalog.getCOSDictionary() .getDictionaryObject(COSName.PAGE_LABELS); if (srcLabels != null) { int destPageCount = destination.getNumberOfPages(); COSArray destNums = null; if (destLabels == null) { destLabels = new COSDictionary(); destNums = new COSArray(); destLabels.setItem(COSName.NUMS, destNums); destCatalog.getCOSDictionary().setItem(COSName.PAGE_LABELS, destLabels); } else { destNums = (COSArray) destLabels.getDictionaryObject(COSName.NUMS); } COSArray srcNums = (COSArray) srcLabels.getDictionaryObject(COSName.NUMS); if (srcNums != null) { for (int i = 0; i < srcNums.size(); i += 2) { COSNumber labelIndex = (COSNumber) srcNums.getObject(i); long labelIndexValue = labelIndex.intValue(); destNums.add(COSInteger.get(labelIndexValue + destPageCount)); destNums.add(cloner.cloneForNewDocument(srcNums.getObject(i + 1))); } } } COSStream destMetadata = (COSStream) destCatalog.getCOSDictionary().getDictionaryObject(COSName.METADATA); COSStream srcMetadata = (COSStream) srcCatalog.getCOSDictionary().getDictionaryObject(COSName.METADATA); if (destMetadata == null && srcMetadata != null) { PDStream newStream = new PDStream(destination, srcMetadata.getUnfilteredStream(), false); newStream.getStream().mergeInto(srcMetadata); newStream.addCompression(); destCatalog.getCOSDictionary().setItem(COSName.METADATA, newStream); } // finally append the pages @SuppressWarnings("unchecked") List<PDPage> pages = srcCatalog.getAllPages(); Iterator<PDPage> pageIter = pages.iterator(); while (pageIter.hasNext()) { PDPage page = pageIter.next(); PDPage newPage = new PDPage((COSDictionary) cloner.cloneForNewDocument(page.getCOSDictionary())); newPage.setCropBox(page.findCropBox()); newPage.setMediaBox(page.findMediaBox()); newPage.setRotation(page.findRotation()); destination.addPage(newPage); } }
From source file:com.fileOperations.ImageToPDF.java
/** * create PDF from image and scales it accordingly to fit in a single page * * @param folderPath String/*from w ww . j ava 2 s . c om*/ * @param imageFileName String * @return String new filename */ public static String createPDFFromImage(String folderPath, String imageFileName) { String pdfFile = FilenameUtils.removeExtension(imageFileName) + ".pdf"; String image = folderPath + imageFileName; PDImageXObject pdImage = null; File imageFile = null; FileInputStream fileStream = null; BufferedImage bim = null; File attachmentLocation = new File(folderPath); if (!attachmentLocation.exists()) { attachmentLocation.mkdirs(); } // the document PDDocument doc = null; PDPageContentStream contentStream = null; try { doc = new PDDocument(); PDPage page = new PDPage(PDRectangle.LETTER); float margin = 72; float pageWidth = page.getMediaBox().getWidth() - 2 * margin; float pageHeight = page.getMediaBox().getHeight() - 2 * margin; if (image.toLowerCase().endsWith(".jpg")) { imageFile = new File(image); fileStream = new FileInputStream(image); pdImage = JPEGFactory.createFromStream(doc, fileStream); // } else if ((image.toLowerCase().endsWith(".tif") // || image.toLowerCase().endsWith(".tiff")) // && TIFFCompression(image) == COMPRESSION_GROUP4) { // imageFile = new File(image); // pdImage = CCITTFactory.createFromFile(doc, imageFile); } else if (image.toLowerCase().endsWith(".gif") || image.toLowerCase().endsWith(".bmp") || image.toLowerCase().endsWith(".png")) { imageFile = new File(image); bim = ImageIO.read(imageFile); pdImage = LosslessFactory.createFromImage(doc, bim); } if (pdImage != null) { if (pdImage.getWidth() > pdImage.getHeight()) { page.setRotation(270); PDRectangle rotatedPage = new PDRectangle(page.getMediaBox().getHeight(), page.getMediaBox().getWidth()); page.setMediaBox(rotatedPage); pageWidth = page.getMediaBox().getWidth() - 2 * margin; pageHeight = page.getMediaBox().getHeight() - 2 * margin; } Dimension pageSize = new Dimension((int) pageWidth, (int) pageHeight); Dimension imageSize = new Dimension(pdImage.getWidth(), pdImage.getHeight()); Dimension scaledDim = PDFBoxTools.getScaledDimension(imageSize, pageSize); float startX = page.getMediaBox().getLowerLeftX() + margin; float startY = page.getMediaBox().getUpperRightY() - margin - scaledDim.height; doc.addPage(page); contentStream = new PDPageContentStream(doc, page); contentStream.drawImage(pdImage, startX, startY, scaledDim.width, scaledDim.height); contentStream.close(); doc.save(folderPath + pdfFile); } } catch (IOException ex) { ExceptionHandler.Handle(ex); return ""; } finally { if (doc != null) { try { doc.close(); } catch (IOException ex) { ExceptionHandler.Handle(ex); return ""; } } } if (fileStream != null) { try { fileStream.close(); } catch (IOException ex) { ExceptionHandler.Handle(ex); return ""; } } if (bim != null) { bim.flush(); } if (imageFile != null) { imageFile.delete(); } return pdfFile; }
From source file:com.fileOperations.ImageToPDF.java
/** * create PDF from image and scales it accordingly to fit in a single page * * @param folderPath String//w ww. jav a 2 s. co m * @param imageFileName String * @return String new filename */ public static String createPDFFromImageNoDelete(String folderPath, String imageFileName) { String pdfFile = FilenameUtils.removeExtension(imageFileName) + ".pdf"; String image = folderPath + imageFileName; PDImageXObject pdImage = null; File imageFile = null; FileInputStream fileStream = null; BufferedImage bim = null; File attachmentLocation = new File(folderPath); if (!attachmentLocation.exists()) { attachmentLocation.mkdirs(); } // the document PDDocument doc = null; PDPageContentStream contentStream = null; try { doc = new PDDocument(); PDPage page = new PDPage(PDRectangle.LETTER); float margin = 72; float pageWidth = page.getMediaBox().getWidth() - 2 * margin; float pageHeight = page.getMediaBox().getHeight() - 2 * margin; if (image.toLowerCase().endsWith(".jpg")) { imageFile = new File(image); fileStream = new FileInputStream(image); pdImage = JPEGFactory.createFromStream(doc, fileStream); // } else if ((image.toLowerCase().endsWith(".tif") // || image.toLowerCase().endsWith(".tiff")) // && TIFFCompression(image) == COMPRESSION_GROUP4) { // imageFile = new File(image); // pdImage = CCITTFactory.createFromFile(doc, imageFile); } else if (image.toLowerCase().endsWith(".gif") || image.toLowerCase().endsWith(".bmp") || image.toLowerCase().endsWith(".png")) { imageFile = new File(image); bim = ImageIO.read(imageFile); pdImage = LosslessFactory.createFromImage(doc, bim); } if (pdImage != null) { if (pdImage.getWidth() > pdImage.getHeight()) { page.setRotation(270); PDRectangle rotatedPage = new PDRectangle(page.getMediaBox().getHeight(), page.getMediaBox().getWidth()); page.setMediaBox(rotatedPage); pageWidth = page.getMediaBox().getWidth() - 2 * margin; pageHeight = page.getMediaBox().getHeight() - 2 * margin; } Dimension pageSize = new Dimension((int) pageWidth, (int) pageHeight); Dimension imageSize = new Dimension(pdImage.getWidth(), pdImage.getHeight()); Dimension scaledDim = PDFBoxTools.getScaledDimension(imageSize, pageSize); float startX = page.getMediaBox().getLowerLeftX() + margin; float startY = page.getMediaBox().getUpperRightY() - margin - scaledDim.height; doc.addPage(page); contentStream = new PDPageContentStream(doc, page); contentStream.drawImage(pdImage, startX, startY, scaledDim.width, scaledDim.height); contentStream.close(); doc.save(folderPath + pdfFile); } } catch (IOException ex) { ExceptionHandler.Handle(ex); return ""; } finally { if (doc != null) { try { doc.close(); } catch (IOException ex) { ExceptionHandler.Handle(ex); return ""; } } } if (fileStream != null) { try { fileStream.close(); } catch (IOException ex) { ExceptionHandler.Handle(ex); return ""; } } if (bim != null) { bim.flush(); } return pdfFile; }
From source file:com.planbase.pdf.layoutmanager.PdfLayoutMgr.java
License:Apache License
/** * Call this when you are through with your current set of pages to commit all pending text and * drawing operations. This is the only method that throws an IOException because the purpose of * PdfLayoutMgr is to buffer all operations until a page is complete so that it can safely be * written to the underlying stream. This method turns the potential pages into real output. * Call when you need a page break, or your document is done and you need to write it out. * * @throws IOException - if there is a failure writing to the underlying stream. *//*w ww . ja va 2 s. c om*/ @SuppressWarnings("UnusedDeclaration") // Part of end-user public interface void logicalPageEnd(LogicalPage lp) throws IOException { // Write out all uncommitted pages. while (unCommittedPageIdx < pages.size()) { PDPage pdPage = new PDPage(); pdPage.setMediaBox(PDPage.PAGE_SIZE_LETTER); if (lp.orientation() == LogicalPage.Orientation.LANDSCAPE) { pdPage.setRotation(90); } PDPageContentStream stream = null; try { stream = new PDPageContentStream(doc, pdPage); doc.addPage(pdPage); if (lp.orientation() == LogicalPage.Orientation.LANDSCAPE) { stream.concatenate2CTM(0, 1, -1, 0, lp.pageWidth(), 0); } stream.setStrokingColorSpace(colorSpace); stream.setNonStrokingColorSpace(colorSpace); PageBuffer pb = pages.get(unCommittedPageIdx); pb.commit(stream); lp.commitBorderItems(stream); stream.close(); // Set to null to show that no exception was thrown and no need to close again. stream = null; } finally { // Let it throw an exception if the closing doesn't work. if (stream != null) { stream.close(); } } unCommittedPageIdx++; } }
From source file:com.planbase.pdf.layoutmanager.PdfLayoutMgr.java
License:Apache License
/** Call this when you are through with your current set of pages to commit all pending text and drawing operations. This is the only method that throws an IOException because the purpose of PdfLayoutMgr is to buffer all operations until a page is complete so that it can safely be written to the underlying stream. This method turns the potential pages into real output. Call when you need a page break, or your document is done and you need to write it out. @throws IOException - if there is a failure writing to the underlying stream. *///w ww . jav a2s . c o m @SuppressWarnings("UnusedDeclaration") // Part of end-user public interface void logicalPageEnd(LogicalPage lp) throws IOException { // Write out all uncommitted pages. while (unCommittedPageIdx < pages.size()) { PDPage pdPage = new PDPage(); pdPage.setMediaBox(PDPage.PAGE_SIZE_LETTER); if (lp.orientation() == LogicalPage.Orientation.LANDSCAPE) { pdPage.setRotation(90); } PDPageContentStream stream = null; try { stream = new PDPageContentStream(doc, pdPage); doc.addPage(pdPage); if (lp.orientation() == LogicalPage.Orientation.LANDSCAPE) { stream.concatenate2CTM(0, 1, -1, 0, lp.pageWidth(), 0); } stream.setStrokingColorSpace(colorSpace); stream.setNonStrokingColorSpace(colorSpace); PageBuffer pb = pages.get(unCommittedPageIdx); pb.commit(stream); lp.commitBorderItems(stream); stream.close(); // Set to null to show that no exception was thrown and no need to close again. stream = null; } finally { // Let it throw an exception if the closing doesn't work. if (stream != null) { stream.close(); } } unCommittedPageIdx++; } }
From source file:de.offis.health.icardea.cied.pdf.extractor.PDFApachePDFBoxExtractor.java
License:Apache License
@SuppressWarnings("unchecked") public byte[] getPDFPages(int fromPageNumber, int toPageNumber) { ByteArrayOutputStream byteArrayOutputStream = null; boolean extractionSuccessful = false; if (pdfDocument != null) { int numberOfPages = getNumberOfPages(); /*//www . j a v a2 s . c om * Check if the given page numbers are in the allowed range. */ if (fromPageNumber > 0 && fromPageNumber <= numberOfPages && toPageNumber > 0 && toPageNumber <= numberOfPages) { /* * Now check if the given fromPageNumber is smaller * as the given toPageNumber. If not swap the numbers. */ if (fromPageNumber > toPageNumber) { int tmpPageNumber = toPageNumber; toPageNumber = fromPageNumber; fromPageNumber = tmpPageNumber; } /* * Now extract the pages * * NOTE * ==== * Since Apache PDFBox v1.5.0 there exists the class * org.apache.pdfbox.util.PageExtractor */ /* boolean isApachePageExtractorAvailable = false; Class<?> pageExtractorClass = null; try { pageExtractorClass = getClass().getClassLoader().loadClass("org.apache.pdfbox.util.PageExtractor"); Constructor<?> pdfExtractConstructor = pageExtractorClass.getConstructor(PDDocument.class, int.class, int.class); Method pdfExtractMethod = pageExtractorClass.getMethod("extract"); isApachePageExtractorAvailable = true; } catch (ClassNotFoundException ex) { } catch (SecurityException ex) { } catch (NoSuchMethodException ex) { } */ try { PDDocument extractedDocumentPages = new PDDocument(); extractedDocumentPages.setDocumentInformation(this.pdfDocument.getDocumentInformation()); extractedDocumentPages.getDocumentCatalog() .setViewerPreferences(this.pdfDocument.getDocumentCatalog().getViewerPreferences()); List<PDPage> pages = (List<PDPage>) this.pdfDocument.getDocumentCatalog().getAllPages(); int pageCounter = 1; for (PDPage page : pages) { if (pageCounter >= fromPageNumber && pageCounter <= toPageNumber) { PDPage importedPdfPage; importedPdfPage = extractedDocumentPages.importPage(page); importedPdfPage.setCropBox(page.findCropBox()); importedPdfPage.setMediaBox(page.findMediaBox()); importedPdfPage.setResources(page.findResources()); importedPdfPage.setRotation(page.findRotation()); } pageCounter++; } // end for byteArrayOutputStream = new ByteArrayOutputStream(); extractedDocumentPages.save(byteArrayOutputStream); extractedDocumentPages.close(); extractionSuccessful = true; } catch (COSVisitorException ex) { // TODO: Create an own exception for PDF processing errors. logger.error("An exception occurred while extracting " + "pages from the input PDF file.", ex); } catch (IOException ex) { // TODO: Create an own exception for PDF processing errors. logger.error("An exception occurred while extracting " + "pages from the input PDF file.", ex); } finally { if (!extractionSuccessful) { byteArrayOutputStream = null; } } // end try..catch..finally } // end if checking range of given pages } // end if (pdfDocument != null) if (byteArrayOutputStream != null) { return byteArrayOutputStream.toByteArray(); } return null; }