List of usage examples for com.itextpdf.text.pdf PdfReader getPageSizeWithRotation
public Rectangle getPageSizeWithRotation(final PdfDictionary page)
From source file:EplanPrinter.PDFPrint.java
License:Open Source License
public String createPDF(String input, String output) throws FileNotFoundException, DocumentException, IOException { heightScalar = 0;/* w w w.j a va2 s . c om*/ //Addition. linh 07.21.2016 bypass owner password PdfReader.unethicalreading = true; PdfReader reader = new PdfReader(input); //Sets up the stamper, which is what adds all the content to the page. pds = new PdfStamper(reader, new FileOutputStream(output)); PdfImportedPage page; page = pds.getImportedPage(reader, 1); PdfContentByte bg; totalPages = reader.getNumberOfPages(); r = new Rectangle[totalPages]; rotation = new int[totalPages]; for (int x = 0; x < totalPages; x++) { r[x] = reader.getPageSizeWithRotation(x + 1); rotation[x] = reader.getPageRotation(x + 1); } mediabox = getDocumentMediaBox(reader, totalPages); //r = reader.getPageSizeWithRotation(1); //setRatio(); bg = pds.getUnderContent(1); heightScalar = 0; return ""; }
From source file:eu.mrbussy.pdfsplitter.Application.java
License:Open Source License
/** * Split the given PDF file into multiple files using pages. * //from w ww . ja v a 2 s.co m * @param filename * - Name of the PDF to split * @param useSubFolder * - Use a separate folder to place the files in. */ public static void SplitFile(File file, boolean useSubFolder) { PdfReader reader = null; String format = null; if (useSubFolder) format = "%1$s%2$s%4$s%2$s_%%03d.%3$s"; else format = "%1$s%2$s_%%03d.%3$s"; String splitFile = String.format(format, FilenameUtils.getFullPath(file.getAbsolutePath()), FilenameUtils.getBaseName(file.getAbsolutePath()), FilenameUtils.getExtension(file.getAbsolutePath()), IOUtils.DIR_SEPARATOR); try { reader = new PdfReader(new FileInputStream(file)); if (reader.getNumberOfPages() > 0) { for (int pageNum = 1; pageNum <= reader.getNumberOfPages(); pageNum++) { System.out.println(String.format(splitFile, pageNum)); String filename = String.format(splitFile, pageNum); Document document = new Document(reader.getPageSizeWithRotation(1)); PdfCopy writer = new PdfCopy(document, new FileOutputStream(filename)); document.open(); // Copy the page from the original PdfImportedPage page = writer.getImportedPage(reader, pageNum); writer.addPage(page); document.close(); writer.close(); } } } catch (Exception ex) { // TODO Implement exception handling ex.printStackTrace(System.err); } finally { if (reader != null) // Always close the stream reader.close(); } }
From source file:eu.mrbussy.pdfsplitter.Splitter.java
License:Open Source License
/** * Split the given PDF file into multiple files using pages. * /*from ww w. ja v a 2 s . co m*/ * @param filename * - Name of the PDF to split * @param useSubFolder * - Use a separate folder to place the files in. */ public static void Run(File file, boolean useSubFolder) { PdfReader reader = null; String format = null; if (useSubFolder) { format = "%1$s%2$s%4$s"; // Directory format try { FileUtils.forceMkdir( new File(String.format(format, FilenameUtils.getFullPath(file.getAbsolutePath()), FilenameUtils.getBaseName(file.getAbsolutePath()), FilenameUtils.getExtension(file.getAbsolutePath()), IOUtils.DIR_SEPARATOR))); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } format = "%1$s%2$s%4$s%2$s_%%03d.%3$s"; // Directory format + filename } else format = "%1$s%2$s_%%03d.%3$s"; String splitFile = String.format(format, FilenameUtils.getFullPath(file.getAbsolutePath()), FilenameUtils.getBaseName(file.getAbsolutePath()), FilenameUtils.getExtension(file.getAbsolutePath()), IOUtils.DIR_SEPARATOR); try { reader = new PdfReader(new FileInputStream(file)); if (reader.getNumberOfPages() > 0) { for (int pageNum = 1; pageNum <= reader.getNumberOfPages(); pageNum++) { System.out.println(String.format(splitFile, pageNum)); String filename = String.format(splitFile, pageNum); Document document = new Document(reader.getPageSizeWithRotation(1)); PdfCopy writer = new PdfCopy(document, new FileOutputStream(filename)); document.open(); // Copy the page from the original PdfImportedPage page = writer.getImportedPage(reader, pageNum); writer.addPage(page); document.close(); writer.close(); } } } catch (Exception ex) { // TODO Implement exception handling ex.printStackTrace(System.err); } finally { if (reader != null) // Always close the stream reader.close(); } }
From source file:fyp.JavaWritePDF.java
public void manipulatePdf(String src, String dest) throws IOException, DocumentException { PdfReader reader = new PdfReader(src); // read source file PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest)); // create destination file stamper.insertPage(reader.getNumberOfPages() + 1, reader.getPageSizeWithRotation(1)); // insert new page Image img = Image.getInstance(IMG); // get instance of image file img.setAbsolutePosition(0, 350);// w w w . j av a 2 s .c om stamper.getOverContent(2).addImage(img); // insert image to new page stamper.close(); // close stamper File delfile = new File(SRC); delfile.delete(); // delete source file respiratorytest.success(); }
From source file:fyp.JavaWritePDF.java
public void manipulatePdf2(String src, String dest) throws IOException, DocumentException { PdfReader reader = new PdfReader(src); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest)); stamper.insertPage(reader.getNumberOfPages() + 1, reader.getPageSizeWithRotation(1)); stamper.insertPage(reader.getNumberOfPages() + 1, reader.getPageSizeWithRotation(1));// create a second new page Image img = Image.getInstance(IMG); Image img2 = Image.getInstance(IMG2); img.setAbsolutePosition(0, 350);//from w w w . ja v a2s . co m img2.setAbsolutePosition(0, 350); stamper.getOverContent(2).addImage(img); stamper.getOverContent(3).addImage(img2); // add the second sessions image to the new page stamper.close(); File delfile = new File(SRC); delfile.delete(); respiratorytest.success(); }
From source file:gov.utah.dts.det.ccl.actions.facility.information.license.reports.LicenseCertificate.java
private static void writePdf(License license, ByteArrayOutputStream ba, HttpServletRequest request) throws DocumentException, BadElementException { SimpleDateFormat df = new SimpleDateFormat("MMMM d, yyyy"); StringBuilder sb;//from w ww .jav a 2 s. c o m // Retrieve the certificate template to use as watermark ServletContext context = request.getSession().getServletContext(); String templatefile = context.getRealPath("/resources") + "/LicenseCertificateTemplate.pdf"; PdfReader reader = getTemplateReader(templatefile); if (reader != null && reader.getNumberOfPages() > 0) { Phrase phrase; // Create new document using the page size of the certificate template document Document document = new Document(reader.getPageSizeWithRotation(1), 0, 0, 0, 0); PdfWriter writer = PdfWriter.getInstance(document, ba); document.open(); // Get the writer under content byte for placing of watermark PdfContentByte under = writer.getDirectContentUnder(); PdfContentByte over = writer.getDirectContent(); // Retrieve the first page of the template document and wrap as an Image to use as new document watermark PdfImportedPage page = writer.getImportedPage(reader, 1); Image img = Image.getInstance(page); // Make sure the image has an absolute page position if (!img.hasAbsoluteX() || !img.hasAbsoluteY()) { img.setAbsolutePosition(0, 0); } under.addImage(img); /* * THE FOLLOWING TWO FUNCTION CALLS DISPLAY THE PAGE MARGINS AND TEXT COLUMN BORDERS FOR DEBUGGING TEXT PLACEMENT. * UNCOMMENT EACH FUNCTION CALL TO HAVE BORDERS DISPLAYED ON THE OUTPUT DOCUMENT. THIS WILL HELP WHEN YOU NEED * TO SEE WHERE TEXT WILL BE PLACED ON THE CERTIFICATE FORM. */ // Show the page margins //showPageMarginBorders(over); // Show the text column borders //showColumnBorders(over); ColumnText ct = new ColumnText(over); ct.setLeading(fixedLeading); // Add Facility Name to column String text = license.getFacility().getName(); if (text != null) { phrase = new Phrase(text.toUpperCase(), mediumfontB); phrase.setLeading(noLeading); ct.addText(phrase); ct.addText(Chunk.NEWLINE); } // Add Facility Site to column text = license.getFacility().getSiteName(); if (text != null) { phrase = new Phrase(text.toUpperCase(), mediumfontB); phrase.setLeading(noLeading); ct.addText(phrase); ct.addText(Chunk.NEWLINE); } // Add Facility Address to column text = license.getFacility().getLocationAddress().getAddressOne(); if (text != null) { phrase = new Phrase(text.toUpperCase(), mediumfontB); phrase.setLeading(noLeading); ct.addText(phrase); ct.addText(Chunk.NEWLINE); } text = license.getFacility().getLocationAddress().getCityStateZip(); if (text != null) { phrase = new Phrase(text.toUpperCase(), mediumfontB); phrase.setLeading(noLeading); ct.addText(phrase); ct.addText(Chunk.NEWLINE); } // Write column to document ct.setAlignment(Element.ALIGN_CENTER); ct.setSimpleColumn(COLUMNS[0][0], COLUMNS[0][1], COLUMNS[0][2], COLUMNS[0][3]); ct.go(); // Add Certification Service Code to column ct = new ColumnText(over); ct.setLeading(fixedLeading); String service = ""; if (license.getSpecificServiceCode() != null && StringUtils.isNotBlank(license.getSpecificServiceCode().getValue()) && DV_TREATMENT.equalsIgnoreCase(license.getSpecificServiceCode().getValue())) { service += DOMESTIC_VIOLENCE; } if (!license.getProgramCodeIds().isEmpty()) { // redmine 25410 mentalHealthLoop: for (PickListValue pkv : license.getProgramCodeIds()) { String program = pkv.getValue(); int idx = program.indexOf(" -"); if (idx >= 0) { String code = program.substring(0, idx); if (MENTAL_HEALTH_CODES.indexOf(code + ":") >= 0) { if (service.length() > 0) { service += " / "; } service += MENTAL_HEALTH; break mentalHealthLoop; } } } substanceAbuseLoop: for (PickListValue pkv : license.getProgramCodeIds()) { String program = pkv.getValue(); int idx = program.indexOf(" -"); if (idx >= 0) { String code = program.substring(0, idx); if (SUBSTANCE_ABUSE_CODES.indexOf(code + ":") >= 0) { if (service.length() > 0) { service += " / "; } service += SUBSTANCE_ABUSE; break substanceAbuseLoop; } } } } if (StringUtils.isNotBlank(license.getServiceCodeDesc())) { if (service.length() > 0) { service += " / "; } service += license.getServiceCodeDesc(); } if (StringUtils.isNotEmpty(service)) { phrase = new Phrase(service.toUpperCase(), mediumfont); phrase.setLeading(noLeading); ct.addText(phrase); ct.addText(Chunk.NEWLINE); } // Add CLIENTS Info to column sb = new StringBuilder("FOR "); if (license.getAgeGroup() == null || license.getAgeGroup().getValue().equalsIgnoreCase("Adult & Youth")) { // Adult & Youth if (license.getAdultTotalSlots() != null) { sb.append(license.getAdultTotalSlots().toString()); } sb.append(" ADULT AND YOUTH CLIENTS"); } else if (license.getAgeGroup().getValue().equalsIgnoreCase("Adult")) { // Adult if (license.getAdultTotalSlots() != null) { // Are male or female counts specified? sb.append(license.getAdultTotalSlots().toString()); sb.append(" ADULT"); if (license.getAdultFemaleCount() != null || license.getAdultMaleCount() != null) { // Does either the male or female count equal the total slot count? if ((license.getAdultFemaleCount() != null && license.getAdultFemaleCount().equals(license.getAdultTotalSlots()))) { sb.append(" FEMALE CLIENTS"); } else if (license.getAdultMaleCount() != null && license.getAdultMaleCount().equals(license.getAdultTotalSlots())) { sb.append(" MALE CLIENTS"); } else { sb.append(" CLIENTS, "); if (license.getAdultMaleCount() != null) { sb.append(license.getAdultMaleCount().toString() + " MALE"); } if (license.getAdultFemaleCount() != null) { if (license.getAdultMaleCount() != null) { sb.append(" AND "); } sb.append(license.getAdultFemaleCount().toString() + " FEMALE"); } if (license.getFromAge() != null || license.getToAge() != null) { sb.append(","); } } } else { sb.append(" CLIENTS"); } } else { sb.append(" ADULT CLIENTS"); } } else { // Youth if (license.getYouthTotalSlots() != null) { // Are male or female counts specified? sb.append(license.getYouthTotalSlots().toString()); sb.append(" YOUTH"); if (license.getYouthFemaleCount() != null || license.getYouthMaleCount() != null) { // Does either the male or female count equal the total slot count? if ((license.getYouthFemaleCount() != null && license.getYouthFemaleCount().equals(license.getYouthTotalSlots()))) { sb.append(" FEMALE CLIENTS"); } else if (license.getYouthMaleCount() != null && license.getYouthMaleCount().equals(license.getYouthTotalSlots())) { sb.append(" MALE CLIENTS"); } else { sb.append(" CLIENTS, "); if (license.getYouthMaleCount() != null) { sb.append(license.getYouthMaleCount().toString() + " MALE"); } if (license.getYouthFemaleCount() != null) { if (license.getYouthMaleCount() != null) { sb.append(" AND "); } sb.append(license.getYouthFemaleCount().toString() + " FEMALE"); } if (license.getFromAge() != null || license.getToAge() != null) { sb.append(","); } } } else { sb.append(" CLIENTS"); } } else { sb.append(" YOUTH CLIENTS"); } } if (license.getFromAge() != null || license.getToAge() != null) { sb.append(" AGES "); if (license.getFromAge() != null) { sb.append(license.getFromAge().toString()); if (license.getToAge() != null) { sb.append(" TO " + license.getToAge().toString()); } else { sb.append(" AND OLDER"); } } else { sb.append("TO " + license.getToAge().toString()); } } phrase = new Phrase(sb.toString(), mediumfont); phrase.setLeading(noLeading); ct.addText(phrase); ct.addText(Chunk.NEWLINE); // Add Certificate Comments if (StringUtils.isNotBlank(license.getCertificateComment())) { phrase = new Phrase(license.getCertificateComment().toUpperCase(), mediumfont); phrase.setLeading(noLeading); ct.addText(phrase); } // Write column to document ct.setAlignment(Element.ALIGN_CENTER); ct.setSimpleColumn(COLUMNS[1][0], COLUMNS[1][1], COLUMNS[1][2], COLUMNS[1][3]); ct.go(); // Add Certificate Start Date if (license.getStartDate() != null) { phrase = new Phrase(df.format(license.getStartDate()), mediumfont); phrase.setLeading(noLeading); ct = new ColumnText(over); ct.setSimpleColumn(phrase, COLUMNS[2][0], COLUMNS[2][1], COLUMNS[2][2], COLUMNS[2][3], fixedLeading, Element.ALIGN_RIGHT); ct.go(); } // Add Certificate End Date if (license.getEndDate() != null) { phrase = new Phrase(df.format(license.getEndDate()), mediumfont); phrase.setLeading(noLeading); ct = new ColumnText(over); ct.setSimpleColumn(phrase, COLUMNS[3][0], COLUMNS[3][1], COLUMNS[3][2], COLUMNS[3][3], fixedLeading, Element.ALIGN_LEFT); ct.go(); } // Add License Number if (license.getLicenseNumber() != null) { phrase = new Phrase(license.getLicenseNumber().toString(), largefontB); phrase.setLeading(noLeading); ct = new ColumnText(over); ct.setSimpleColumn(phrase, COLUMNS[4][0], COLUMNS[4][1], COLUMNS[4][2], COLUMNS[4][3], numberLeading, Element.ALIGN_CENTER); ct.go(); } document.close(); } }
From source file:mergevoucher.MainJFrame.java
private void deletePages(File file, String str) throws IOException, DocumentException { //open the old pdf file and open a blank new one String fullFileName = file.getPath(); //System.out.println(fullFileName); PdfReader reader = new PdfReader(fullFileName); Document document = new Document(reader.getPageSizeWithRotation(1)); String out = fullFileName.replaceFirst(".pdf", "(new).pdf"); PdfCopy copy = new PdfCopy(document, new FileOutputStream(out)); document.open();//from w ww .ja va 2 s.c o m int pdfPageNumber = reader.getNumberOfPages(); //get pdf page number //change pageNumber string to int array Boolean[] preservePages = getPages(pdfPageNumber, str); //copy pages except need delete to new pdf file for (int i = 1; i <= pdfPageNumber; i++) { //filter not preserve pages if (preservePages[i]) { //if preserve,copy;else bypass //String content = PdfTextExtractor.getTextFromPage(reader, i); //?i; copy.addPage(copy.getImportedPage(reader, i)); } } System.out.println("New pdf file is:" + fullFileName.replaceFirst(".pdf", "(new).pdf")); //close files reader.close(); document.close(); copy.close(); }
From source file:org.alfresco.extension.countersign.action.executer.PDFAddSignatureFieldActionExecuter.java
License:Open Source License
/** * @see org.alfresco.repo.action.executer.ActionExecuterAbstractBase#executeImpl(org.alfresco.service.cmr.repository.NodeRef, * org.alfresco.service.cmr.repository.NodeRef) */// w w w.j av a2 s.co m protected void executeImpl(Action ruleAction, NodeRef actionedUponNodeRef) { NodeService ns = serviceRegistry.getNodeService(); if (ns.exists(actionedUponNodeRef) == false) { // node doesn't exist - can't do anything return; } String fieldName = (String) ruleAction.getParameterValue(PARAM_FIELDNAME); String position = (String) ruleAction.getParameterValue(PARAM_POSITION); JSONObject box; int page = -1; // parse out the position JSON JSONObject positionObj = null; try { positionObj = (JSONObject) parser.parse(position); } catch (ParseException e) { logger.error("Could not parse position JSON from Share"); throw new AlfrescoRuntimeException("Could not parse position JSON from Share"); } // get the page page = Integer.parseInt(String.valueOf(positionObj.get("page"))); // get the box box = (JSONObject) positionObj.get("box"); try { // open original pdf ContentReader pdfReader = getReader(actionedUponNodeRef); PdfReader reader = new PdfReader(pdfReader.getContentInputStream()); OutputStream cos = serviceRegistry.getContentService() .getWriter(actionedUponNodeRef, ContentModel.PROP_CONTENT, true).getContentOutputStream(); PdfStamper stamp = new PdfStamper(reader, cos); // does a field with this name already exist? AcroFields allFields = stamp.getAcroFields(); // if this doc is already signed, cannot add a new sig field without if (allFields.getSignatureNames() != null && allFields.getSignatureNames().size() > 0) { throw new AlfrescoRuntimeException("This document has signatures applied, " + "adding a new signature field would invalidate existing signatures"); } // cant create duplicate field names if (allFields.getFieldType(fieldName) == AcroFields.FIELD_TYPE_SIGNATURE) { throw new AlfrescoRuntimeException( "A signature field named " + fieldName + " already exists in this document"); } // create the signature field Rectangle pageRect = reader.getPageSizeWithRotation(page); Rectangle sigRect = positionBlock(pageRect, box); PdfFormField sigField = stamp.addSignature(fieldName, page, sigRect.getLeft(), sigRect.getBottom(), sigRect.getRight(), sigRect.getTop()); // style the field (no borders) sigField.setBorder(new PdfBorderArray(0, 0, 0)); sigField.setBorderStyle(new PdfBorderDictionary(0, PdfBorderDictionary.STYLE_SOLID)); allFields.regenerateField(fieldName); // apply the change and close streams stamp.close(); reader.close(); cos.close(); // once the signature field has been added, apply the sig field aspect if (!ns.hasAspect(actionedUponNodeRef, CounterSignSignatureModel.ASPECT_SIGNABLE)) { ns.addAspect(actionedUponNodeRef, CounterSignSignatureModel.ASPECT_SIGNABLE, null); } // now update the signature fields metadata Serializable currentFields = ns.getProperty(actionedUponNodeRef, CounterSignSignatureModel.PROP_SIGNATUREFIELDS); ArrayList<String> fields = new ArrayList<String>(); if (currentFields != null) { fields.addAll((List<String>) currentFields); } fields.add(fieldName); ns.setProperty(actionedUponNodeRef, CounterSignSignatureModel.PROP_SIGNATUREFIELDS, fields); } catch (IOException ioex) { throw new AlfrescoRuntimeException(ioex.getMessage()); } catch (DocumentException dex) { throw new AlfrescoRuntimeException(dex.getMessage()); } }
From source file:org.alfresco.extension.countersign.action.executer.PDFSignatureProviderActionExecuter.java
License:Open Source License
/** * @see org.alfresco.repo.action.executer.ActionExecuterAbstractBase#executeImpl(org.alfresco.service.cmr.repository.NodeRef, * org.alfresco.service.cmr.repository.NodeRef) *///from w ww . j a v a 2 s. c o m protected void executeImpl(Action ruleAction, NodeRef actionedUponNodeRef) { if (serviceRegistry.getNodeService().exists(actionedUponNodeRef) == false) { // node doesn't exist - can't do anything return; } String location = (String) ruleAction.getParameterValue(PARAM_LOCATION); String geolocation = (String) ruleAction.getParameterValue(PARAM_GEOLOCATION); String reason = (String) ruleAction.getParameterValue(PARAM_REASON); String position = (String) ruleAction.getParameterValue(PARAM_POSITION); String keyPassword = (String) ruleAction.getParameterValue(PARAM_KEY_PASSWORD); String signatureJson = (String) ruleAction.getParameterValue(PARAM_SIGNATURE_JSON); Boolean visible = (Boolean) ruleAction.getParameterValue(PARAM_VISIBLE); Boolean graphic = (Boolean) ruleAction.getParameterValue(PARAM_GRAPHIC); boolean useSignatureField = false; String user = AuthenticationUtil.getRunAsUser(); String positionType = "predefined"; String positionLoc = "center"; JSONObject box; int page = -1; // parse out the position JSON JSONObject positionObj = null; try { positionObj = (JSONObject) parser.parse(position); } catch (ParseException e) { logger.error("Could not parse position JSON from Share"); throw new AlfrescoRuntimeException("Could not parse position JSON from Share"); } // get the page page = Integer.parseInt(String.valueOf(positionObj.get("page"))); // get the positioning type positionType = String.valueOf(positionObj.get("type")); // get the position (field or predefined) positionLoc = String.valueOf(positionObj.get("position")); // get the box (if required) box = (JSONObject) positionObj.get("box"); int width = 350; int height = 75; File tempDir = null; // current date, used for both signing the PDF and creating the // associated signature object Calendar now = Calendar.getInstance(); try { // get the keystore, pk and cert chain SignatureProvider signatureProvider = signatureProviderFactory.getSignatureProvider(user); KeyStore keystore = signatureProvider.getUserKeyStore(keyPassword); PrivateKey key = (PrivateKey) keystore.getKey(alias, keyPassword.toCharArray()); Certificate[] chain = keystore.getCertificateChain(alias); // open original pdf ContentReader pdfReader = getReader(actionedUponNodeRef); PdfReader reader = new PdfReader(pdfReader.getContentInputStream()); // create temp dir to store file File alfTempDir = TempFileProvider.getTempDir(); tempDir = new File(alfTempDir.getPath() + File.separatorChar + actionedUponNodeRef.getId()); tempDir.mkdir(); File file = new File(tempDir, serviceRegistry.getFileFolderService().getFileInfo(actionedUponNodeRef).getName()); OutputStream cos = serviceRegistry.getContentService() .getWriter(actionedUponNodeRef, ContentModel.PROP_CONTENT, true).getContentOutputStream(); PdfStamper stamp = PdfStamper.createSignature(reader, cos, '\0', file, true); PdfSignatureAppearance sap = stamp.getSignatureAppearance(); sap.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED); // set reason for signature, location of signer, and date sap.setReason(reason); sap.setLocation(location); sap.setSignDate(now); // get the image for the signature BufferedImage sigImage = SignatureToImage.convertJsonToImage(signatureJson, width, height); // save the signature image back to the signatureProvider signatureProvider.saveSignatureImage(sigImage, signatureJson); if (visible) { //if this is a graphic sig, set the graphic here if (graphic) { sap.setRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC); sap.setSignatureGraphic(Image.getInstance(sigImage, Color.WHITE)); } else { sap.setRenderingMode(PdfSignatureAppearance.RenderingMode.NAME_AND_DESCRIPTION); } // either insert the sig at a defined field or at a defined position / drawn loc if (positionType.equalsIgnoreCase(POSITION_TYPE_PREDEFINED)) { Rectangle pageRect = reader.getPageSizeWithRotation(page); sap.setVisibleSignature(positionBlock(positionLoc, pageRect, width, height), page, null); } else if (positionType.equalsIgnoreCase(POSITION_TYPE_DRAWN)) { Rectangle pageRect = reader.getPageSizeWithRotation(page); sap.setVisibleSignature(positionBlock(pageRect, box), page, null); } else { sap.setVisibleSignature(positionLoc); useSignatureField = true; } } // close the stamp, applying the changes to the PDF stamp.close(); reader.close(); cos.close(); //delete the temp file file.delete(); // apply the "signed" aspect serviceRegistry.getNodeService().addAspect(actionedUponNodeRef, CounterSignSignatureModel.ASPECT_SIGNED, new HashMap<QName, Serializable>()); // create a "signature" node and associate it with the signed doc addSignatureNodeAssociation(actionedUponNodeRef, location, reason, useSignatureField ? positionLoc : "none", now.getTime(), geolocation, page, positionLoc); } catch (IOException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (ContentIOException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (DocumentException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (KeyStoreException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (UnrecoverableKeyException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (NoSuchAlgorithmException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } finally { if (tempDir != null) { try { tempDir.delete(); } catch (Exception ex) { throw new AlfrescoRuntimeException(ex.getMessage(), ex); } } } }
From source file:org.alfresco.extension.pdftoolkit.repo.action.executer.PDFSignatureActionExecuter.java
License:Apache License
/** * /*w w w . j a va2 s .c o m*/ * @param ruleAction * @param actionedUponNodeRef * @param actionedUponContentReader */ protected void doSignature(Action ruleAction, NodeRef actionedUponNodeRef, ContentReader actionedUponContentReader) { NodeRef privateKey = (NodeRef) ruleAction.getParameterValue(PARAM_PRIVATE_KEY); String location = (String) ruleAction.getParameterValue(PARAM_LOCATION); String position = (String) ruleAction.getParameterValue(PARAM_POSITION); String reason = (String) ruleAction.getParameterValue(PARAM_REASON); String visibility = (String) ruleAction.getParameterValue(PARAM_VISIBILITY); String keyPassword = (String) ruleAction.getParameterValue(PARAM_KEY_PASSWORD); String keyType = (String) ruleAction.getParameterValue(PARAM_KEY_TYPE); int height = getInteger(ruleAction.getParameterValue(PARAM_HEIGHT)); int width = getInteger(ruleAction.getParameterValue(PARAM_WIDTH)); int pageNumber = getInteger(ruleAction.getParameterValue(PARAM_PAGE)); // New keystore parameters String alias = (String) ruleAction.getParameterValue(PARAM_ALIAS); String storePassword = (String) ruleAction.getParameterValue(PARAM_STORE_PASSWORD); int locationX = getInteger(ruleAction.getParameterValue(PARAM_LOCATION_X)); int locationY = getInteger(ruleAction.getParameterValue(PARAM_LOCATION_Y)); File tempDir = null; ContentWriter writer = null; KeyStore ks = null; try { // get a keystore instance by if (keyType == null || keyType.equalsIgnoreCase(KEY_TYPE_DEFAULT)) { ks = KeyStore.getInstance(KeyStore.getDefaultType()); } else if (keyType.equalsIgnoreCase(KEY_TYPE_PKCS12)) { ks = KeyStore.getInstance("pkcs12"); } else { throw new AlfrescoRuntimeException("Unknown key type " + keyType + " specified"); } // open the reader to the key and load it ContentReader keyReader = getReader(privateKey); ks.load(keyReader.getContentInputStream(), storePassword.toCharArray()); // set alias // String alias = (String) ks.aliases().nextElement(); PrivateKey key = (PrivateKey) ks.getKey(alias, keyPassword.toCharArray()); Certificate[] chain = ks.getCertificateChain(alias); // open original pdf ContentReader pdfReader = getReader(actionedUponNodeRef); PdfReader reader = new PdfReader(pdfReader.getContentInputStream()); // create temp dir to store file File alfTempDir = TempFileProvider.getTempDir(); tempDir = new File(alfTempDir.getPath() + File.separatorChar + actionedUponNodeRef.getId()); tempDir.mkdir(); File file = new File(tempDir, serviceRegistry.getFileFolderService().getFileInfo(actionedUponNodeRef).getName()); FileOutputStream fout = new FileOutputStream(file); PdfStamper stamp = PdfStamper.createSignature(reader, fout, '\0'); PdfSignatureAppearance sap = stamp.getSignatureAppearance(); sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); // set reason for signature and location of signer sap.setReason(reason); sap.setLocation(location); if (visibility.equalsIgnoreCase(PDFSignatureActionExecuter.VISIBILITY_VISIBLE)) { //create the signature rectangle using either the provided position or //the exact coordinates, if provided if (position != null && !position.trim().equalsIgnoreCase("")) { Rectangle pageRect = reader.getPageSizeWithRotation(pageNumber); sap.setVisibleSignature(positionSignature(position, pageRect, width, height), pageNumber, null); } else { sap.setVisibleSignature( new Rectangle(locationX, locationY, locationX + width, locationY - height), pageNumber, null); } } stamp.close(); //can't use BasePDFActionExecuter.getWriter here need the nodeRef of the destination NodeRef destinationNode = createDestinationNode(file.getName(), (NodeRef) ruleAction.getParameterValue(PARAM_DESTINATION_FOLDER), actionedUponNodeRef); writer = serviceRegistry.getContentService().getWriter(destinationNode, ContentModel.PROP_CONTENT, true); writer.setEncoding(actionedUponContentReader.getEncoding()); writer.setMimetype(FILE_MIMETYPE); writer.putContent(file); file.delete(); //if useAspect is true, store some additional info about the signature in the props if (useAspect) { serviceRegistry.getNodeService().addAspect(destinationNode, PDFToolkitModel.ASPECT_SIGNED, new HashMap<QName, Serializable>()); serviceRegistry.getNodeService().setProperty(destinationNode, PDFToolkitModel.PROP_REASON, reason); serviceRegistry.getNodeService().setProperty(destinationNode, PDFToolkitModel.PROP_LOCATION, location); serviceRegistry.getNodeService().setProperty(destinationNode, PDFToolkitModel.PROP_SIGNATUREDATE, new java.util.Date()); serviceRegistry.getNodeService().setProperty(destinationNode, PDFToolkitModel.PROP_SIGNEDBY, AuthenticationUtil.getRunAsUser()); } } catch (IOException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (KeyStoreException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (ContentIOException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (NoSuchAlgorithmException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (CertificateException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (UnrecoverableKeyException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (DocumentException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } finally { if (tempDir != null) { try { tempDir.delete(); } catch (Exception ex) { throw new AlfrescoRuntimeException(ex.getMessage(), ex); } } } }