List of usage examples for org.apache.pdfbox.pdmodel PDDocument getNumberOfPages
public int getNumberOfPages()
From source file:PDFTextExtract.java
License:Apache License
/** * This will parse the documents data.//from w w w .j av a2 s. c o m * * @throws IOException If there is an error parsing the document. */ public void process() throws IOException { PDDocument document = null; String res = null; OutputStream os = null; try { // Target PDF file. document = PDDocument.load(new File(this.PDFFilePath)); // Extract Text from PDF ordered by page number. for (int i = 1; i <= document.getNumberOfPages(); i++) { System.out.println("processing page " + i + "..."); _tmp.clear(); PDFTextExtract stripper = new PDFTextExtract(); // Tell PDFBox to sort the text positions. stripper.setSortByPosition(true); // Extract only one page. stripper.setStartPage(i); stripper.setEndPage(i); // Convert class `textPositions` into `Text`. // Save conversion result in `_tmp`. Writer dummy = new OutputStreamWriter(new ByteArrayOutputStream()); stripper.writeText(document, dummy); // Skip if nothing converted. if (_tmp.isEmpty()) continue; // Concate result into string. for (Text now : _tmp) { res += now.unicode; } } // Write result to file. os = new FileOutputStream(OutputFilepath); os.write(res.getBytes()); System.out.println("processing completed."); } finally { if (document != null) { document.close(); } if (os != null) { os.close(); } } }
From source file:adams.flow.transformer.PDFRenderPages.java
License:Open Source License
/** * Executes the flow item./* w w w . j a v a2 s . c o m*/ * * @return null if everything is fine, otherwise error message */ @Override protected String doExecute() { String result; File file; PDDocument doc; BufferedImageContainer cont; PDFRenderer renderer; BufferedImage img; MessageCollection errors; result = null; // get file if (m_InputToken.getPayload() instanceof File) file = (File) m_InputToken.getPayload(); else file = new PlaceholderFile((String) m_InputToken.getPayload()); doc = PDFBox.load(file); if (doc != null) { if (isLoggingEnabled()) getLogger().info("Rendering pages from '" + file + "'"); m_Pages.setMax(doc.getNumberOfPages()); renderer = new PDFRenderer(doc); errors = new MessageCollection(); for (int page : m_Pages.getIntIndices()) { if (isLoggingEnabled()) getLogger().info("Rendering page #" + (page + 1)); try { img = renderer.renderImageWithDPI(page, m_DPI); cont = new BufferedImageContainer(); cont.setImage(img); cont.getReport().setStringValue("File", file.getAbsolutePath()); cont.getReport().setNumericValue("Page", (page + 1)); m_Images.add(cont); } catch (Exception e) { errors.add(handleException("Failed to render page #" + (page + 1) + " from " + file, e)); } } if (!errors.isEmpty()) result = errors.toString(); } else { result = "Failed to load PDF document: " + file; } return result; }
From source file:at.gv.egiz.pdfas.lib.impl.pdfbox.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/* w ww. j a v a 2s. c o m*/ * The PDF document. * @param pdf_table * The PDFPTable to be placed. * @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, boolean legacy32, boolean legacy40) 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 = (PDPage) pdfDataSource.getDocumentCatalog().getAllPages().get(page - 1); PDRectangle cropBox = pdPage.getCropBox(); // fallback to MediaBox if Cropbox not available! if (cropBox == null) { cropBox = pdPage.findCropBox(); } if (cropBox == null) { cropBox = pdPage.findMediaBox(); } // getPagedimensions // Rectangle psize = reader.getPageSizeWithRotation(page); // int page_rotation = reader.getPageRotation(page); // Integer rotation = pdPage.getRotation(); // int page_rotation = rotation.intValue(); int rotation = pdPage.findRotation(); 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); 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.pdfbox2.positioning.Positioning.java
License:EUPL
/** * Sets the width of the table according to the layout of the document and * calculates the y position where the PDFPTable should be placed. * * @param pdfDataSource//from w ww .jav a2s. c o 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.pdfbox.PADESPDFBOXSigner.java
License:EUPL
public void signPDF(PDFObject genericPdfObject, RequestedSignature requestedSignature, PDFASSignatureInterface genericSigner) throws PdfAsException { String fisTmpFile = null;//w w w . j a v a 2 s . 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 ww w. j av a2 s. c om*/ 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:au.org.alfred.icu.pdf.services.factories.ICUDischargeSummaryFactory.java
public static String loadDischargePDF(InputStream file) throws IOException { String pdf_str = null;// w w w . j a va 2 s . c om PDDocument doc = PDDocument.load(file); int pages = doc.getNumberOfPages(); //System.out.println(pages); PDFTextStripper txt = new PDFTextStripper(); txt.setStartPage(1); txt.setEndPage(1); pdf_str = txt.getText(doc); /*for(Iterator<COSObject> pdfItr = doc.getDocument().getObjects().iterator(); pdfItr.hasNext();) { COSObject inner = pdfItr.next(); }*/ //pdf_str = doc.getDocument().getObjects(); doc.close(); return pdf_str; }
From source file:au.org.alfred.icu.pdf.services.factories.ICUDischargeSummaryFactory.java
private static int createNewPage(PDDocument pdf, PDPage pg_content, PDPageContentStream cs, int yCursor, DischargeSummaryData data) throws IOException { yCursor = 147;/*from w w w.ja va 2 s. co m*/ int temp = 0; createPageTemplate(cs, leftMargin, pageHeight, pageWidth, data); if (pdf.getNumberOfPages() == 0) { drawBox(cs, leftMargin, pageHeight - (yCursor + 51), 530, 72, 1, darkGreen, Color.WHITE); cs.beginText(); cs.setFont(PDType1Font.TIMES_BOLD, 10); cs.setNonStrokingColor(darkGreen); cs.moveTextPositionByAmount(5 + leftMargin, pageHeight - yCursor - 1); cs.drawString("ICU Admission Date"); cs.endText(); //cs.addRect(leftMargin+5, pageHeight-(yCursor+14), 100, 14); drawBoxAndText(cs, leftMargin + 5, pageHeight - (yCursor + 17), 100, 14, 1, darkGreen, Color.WHITE, Color.BLACK, data.getWardAdmDate(), PDType1Font.TIMES_ROMAN, 10); cs.beginText(); cs.setFont(PDType1Font.TIMES_BOLD, 10); cs.setNonStrokingColor(darkGreen); cs.moveTextPositionByAmount(110 + leftMargin, pageHeight - yCursor - 1); cs.drawString("ICU Discharge Date"); cs.endText(); //cs.addRect(leftMargin+5, pageHeight-(yCursor+14), 100, 14); drawBoxAndText(cs, leftMargin + 110, pageHeight - (yCursor + 17), 100, 14, 1, darkGreen, Color.WHITE, Color.BLACK, data.getWardExitDate(), PDType1Font.TIMES_ROMAN, 10); cs.beginText(); cs.setFont(PDType1Font.TIMES_BOLD, 10); cs.setNonStrokingColor(darkGreen); cs.moveTextPositionByAmount(leftMargin + 215, pageHeight - yCursor - 1); cs.drawString("ICU length of stay"); cs.endText(); //cs.addRect(leftMargin+5, pageHeight-(yCursor+14), 100, 14); drawBoxAndText(cs, leftMargin + 215, pageHeight - (yCursor + 17), 100, 14, 1, darkGreen, Color.WHITE, Color.BLACK, data.getLOSHours().concat(" hours (").concat(data.getLOSDays()).concat(" days)"), PDType1Font.TIMES_ROMAN, 10); cs.beginText(); cs.setFont(PDType1Font.TIMES_BOLD, 10); cs.setNonStrokingColor(darkGreen); cs.moveTextPositionByAmount(320 + leftMargin, pageHeight - yCursor - 1); cs.drawString("Delayed Discharge"); cs.endText(); //cs.addRect(leftMargin+5, pageHeight-(yCursor+14), 100, 14); drawBoxAndText(cs, leftMargin + 320, pageHeight - (yCursor + 17), 80, 14, 1, darkGreen, Color.WHITE, Color.BLACK, data.getDelayed(), PDType1Font.TIMES_ROMAN, 10); cs.beginText(); cs.setFont(PDType1Font.TIMES_BOLD, 10); cs.setNonStrokingColor(darkGreen); cs.moveTextPositionByAmount(405 + leftMargin, pageHeight - yCursor - 1); cs.drawString("Early Discharge"); cs.endText(); //cs.addRect(leftMargin+5, pageHeight-(yCursor+14), 100, 14); drawBoxAndText(cs, leftMargin + 405, pageHeight - (yCursor + 17), 80, 14, 1, darkGreen, Color.WHITE, Color.BLACK, data.getEarlyDischarge(), PDType1Font.TIMES_ROMAN, 10); cs.beginText(); cs.setFont(PDType1Font.TIMES_BOLD, 10); cs.setNonStrokingColor(darkGreen); cs.moveTextPositionByAmount(490 + leftMargin, pageHeight - yCursor - 1); cs.drawString("Adm #"); cs.endText(); //cs.addRect(leftMargin+5, pageHeight-(yCursor+14), 100, 14); drawBoxAndText(cs, leftMargin + 490, pageHeight - (yCursor + 17), 30, 14, 1, darkGreen, Color.WHITE, Color.BLACK, data.getAdmNumber(), PDType1Font.TIMES_ROMAN, 10); yCursor += 34; cs.beginText(); cs.setFont(PDType1Font.TIMES_BOLD, 10); cs.setNonStrokingColor(darkGreen); cs.moveTextPositionByAmount(5 + leftMargin, pageHeight - yCursor - 1 + 7); cs.drawString("APACHE III-J Diagnosis"); cs.endText(); drawBoxAndText(cs, leftMargin + 120, pageHeight - yCursor - 1, 400, 15, 1, darkGreen, Color.WHITE, Color.BLACK, data.getApacheIII(), PDType1Font.TIMES_ROMAN, 10); if (data.getCurrentLocation() != null) { yCursor += 15; cs.beginText(); cs.setFont(PDType1Font.TIMES_BOLD, 10); cs.setNonStrokingColor(darkGreen); cs.moveTextPositionByAmount(5 + leftMargin, pageHeight - yCursor - 1 + 7); cs.drawString("Destination"); cs.endText(); drawBoxAndText(cs, leftMargin + 120, pageHeight - yCursor - 1, 400, 15, 1, darkGreen, Color.WHITE, Color.BLACK, data.getCurrentLocation().toUpperCase(), PDType1Font.TIMES_ROMAN, 10); } yCursor += 15; if (data.getResus() != null) { int k = 0; String[][] table = new String[data.getResus().size() + 1][6]; table[k][0] = "For CPR"; table[k][1] = "For Intubation"; table[k][2] = "For Defib"; table[k][3] = "For ICU Readmit"; table[k][4] = "Modified MET Criteria?"; table[k][5] = ""; k++; for (TblResusPlan m : data.getResus()) { table[k][0] = m.getRCpr() ? "Yes" : "No"; table[k][1] = m.getRIntub() ? "Yes" : "No"; table[k][2] = m.getRDefib() ? "Yes" : "No"; table[k][3] = m.getRReadmit() ? "Yes" : "No"; table[k][4] = "".equals(m.getRMetReason()) ? "No" : m.getRMetReason(); table[k][5] = ""; k++; } //System.out.println(yCursor); temp = getTableHeight(pg_content, cs, pageHeight - yCursor, leftMargin, table, PDType1Font.TIMES_BOLD, PDType1Font.TIMES_ROMAN, 10); if ((yCursor + temp + 30) > (pageHeight - footerHeight)) { pg_content = newPageBuilder(pdf, pg_content, cs, data, yCursor); cs = new PDPageContentStream(pdf, pg_content); yCursor = createNewPage(pdf, pg_content, cs, yCursor, data); } yCursor += 10; yCursor += drawTable(pg_content, cs, pageHeight - yCursor, leftMargin, table, PDType1Font.TIMES_BOLD, PDType1Font.TIMES_ROMAN, 10); yCursor += 20; } if (data.getNic() != null) { int k = 0; String[][] table = new String[data.getNic().size() + 1][6]; table[k][0] = "Assessed Nicotine Dependent"; table[k][1] = "Management Offered"; table[k][2] = "Assessment Date"; table[k][3] = "Pharmacist"; table[k][4] = ""; table[k][5] = ""; k++; for (TblNicotine m : data.getNic()) { table[k][0] = m.getNicDependent() == null ? "N/A" : (m.getNicDependent() == 1 ? "Yes" : "No"); table[k][1] = m.getNicMgmOffered() == null ? "N/A" : (m.getNicMgmOffered() == 1 ? "Yes" : "No"); table[k][2] = m.getNicDateAssess() == null ? "N/A" : new SimpleDateFormat("dd/MM/yy").format(m.getNicDateAssess()); table[k][3] = m.getNicPharmacist() == null ? "N/A" : m.getNicPharmacist(); table[k][4] = ""; table[k][5] = ""; k++; } //System.out.println(yCursor); temp = getTableHeight(pg_content, cs, pageHeight - yCursor, leftMargin, table, PDType1Font.TIMES_BOLD, PDType1Font.TIMES_ROMAN, 10); if ((yCursor + temp + 30) > (pageHeight - footerHeight)) { pg_content = newPageBuilder(pdf, pg_content, cs, data, yCursor); cs = new PDPageContentStream(pdf, pg_content); yCursor = createNewPage(pdf, pg_content, cs, yCursor, data); } yCursor += 10; yCursor += drawTable(pg_content, cs, pageHeight - yCursor, leftMargin, table, PDType1Font.TIMES_BOLD, PDType1Font.TIMES_ROMAN, 10); yCursor += 20; } } return yCursor; }
From source file:au.org.alfred.icu.pdf.services.factories.tests.PDFBoxPrintingFactoryTest.java
@Test public void canCreatePDF() throws IOException { PDDocument pdf = new PDDocument(); ICUDischargeSummaryFactory.createDischargeSummaryPDF(pdf); assertFalse(pdf.getNumberOfPages() == 0); }
From source file:au.org.alfred.icu.pdf.services.factories.tests.PDFBoxPrintingFactoryTest.java
@Test public void canSetPageContent() { try {/*from ww w . j a v a 2 s . c om*/ PDDocument pdf = new PDDocument(); ByteArrayOutputStream output = new ByteArrayOutputStream(); String visitNumber = "ALFI1148735"; String icuVisitNumber = "41604"; String patientId = "ALF6216718"; String pdfName = ICUDischargeSummaryFactory.createContent(pdf, icuVisitNumber, visitNumber, patientId, "Miguel de Sousa", "760"); String user = "desousami"; String domain = "BAYSIDEHEALTH"; String passwd = "bkdr4ICUm3k"; NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(domain, user, passwd); String path = "smb://alfapps01/apps/ICUApps/CernerDischarge/" + pdfName; System.out.println(path); //SmbFile sFile = new SmbFile(path, auth); //SmbFileOutputStream sfos = new SmbFileOutputStream(sFile); //pdf.save(output); //sfos.write(output.toByteArray()); //output.close(); ICUDischargeSummaryFactory.saveDocument("/home/miguel/pdftest/" + pdfName, pdf); assertTrue(pdf.getNumberOfPages() > 0); pdf.close(); } catch (COSVisitorException ex) { ex.printStackTrace(System.out); Logger.getLogger(PDFBoxPrintingFactoryTest.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { ex.printStackTrace(System.out); Logger.getLogger(PDFBoxPrintingFactoryTest.class.getName()).log(Level.SEVERE, null, ex); } }