List of usage examples for com.lowagie.text.pdf PdfDictionary put
public void put(PdfName key, PdfObject object)
PdfObject
as value with the specified PdfName
as key in this map. From source file:SignPdf.java
License:Open Source License
/** * Add a signature and a cryptographic timestamp to a pdf document. See www.ietf.org/rfc/rfc3161.txt. Proves that this * pdf had the current content at the current point in time. * * @param originalPdf//from ww w. j a va 2 s.c om * @param targetPdf * @param pk * @param certChain * @param revoked * @param tsaAddress * address of a rfc 3161 compatible timestamp server * @param reason * reason for the signature * @param location * location of signing * @param contact * emailaddress of the person who is signing * @throws IOException * @throws DocumentException * @throws SignatureException */ public static void signAndTimestamp(final InputStream originalPdf, final OutputStream targetPdf, final PrivateKey pk, final X509Certificate[] certChain, final CRL[] revoked, final String tsaAddress, final String reason, final String location, final String contact) throws IOException, DocumentException, SignatureException { // only an estimate, depends on the certificates returned by the TSA final int timestampSize = 4400; Security.addProvider(new BouncyCastleProvider()); final PdfReader reader = new PdfReader(originalPdf); final PdfStamper stamper = PdfStamper.createSignature(reader, targetPdf, '\0'); final PdfSignatureAppearance sap = stamper.getSignatureAppearance(); // comment next lines to have an invisible signature Rectangle cropBox = reader.getCropBox(1); float width = 50; float height = 50; Rectangle rectangle = new Rectangle(cropBox.getRight(width) - 20, cropBox.getTop(height) - 20, cropBox.getRight() - 20, cropBox.getTop() - 20); sap.setVisibleSignature(rectangle, 1, null); //sap.setVisibleSignature(new Rectangle(450, 650, 500, 700), 1, null); sap.setLayer2Text(""); final PdfSigGenericPKCS sig = new PdfSigGenericPKCS.PPKMS("BC"); final HashMap<PdfName, Integer> exclusionSizes = new HashMap<PdfName, Integer>(); // some informational fields sig.setReason(reason); sig.setLocation(location); sig.setContact(contact); sig.setName(PdfPKCS7.getSubjectFields(certChain[0]).getField("CN")); sig.setDate(new PdfDate(Calendar.getInstance())); // signing stuff final byte[] digest = new byte[256]; final byte[] rsaData = new byte[20]; sig.setExternalDigest(digest, rsaData, "RSA"); sig.setSignInfo(pk, certChain, revoked); final PdfString contents = (PdfString) sig.get(PdfName.CONTENTS); // *2 to get hex size, +2 for delimiters PdfLiteral contentsLit = new PdfLiteral((contents.toString().length() + timestampSize) * 2 + 2); exclusionSizes.put(PdfName.CONTENTS, new Integer(contentsLit.getPosLength())); sig.put(PdfName.CONTENTS, contentsLit); // certification; will display dialog or blue bar in Acrobat Reader sap.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED); // process all the information set above sap.setCryptoDictionary(sig); sap.preClose(exclusionSizes); // calculate digest (hash) try { final MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); final byte[] buf = new byte[8192]; int n; final InputStream inp = sap.getRangeStream(); while ((n = inp.read(buf)) != -1) { messageDigest.update(buf, 0, n); } final byte[] hash = messageDigest.digest(); // make signature (SHA1 the hash, prepend algorithm ID, pad, and encrypt with RSA) final Signature sign = Signature.getInstance("SHA1withRSA"); sign.initSign(pk); sign.update(hash); final byte[] signature = sign.sign(); // prepare the location of the signature in the target PDF contentsLit = (PdfLiteral) sig.get(PdfName.CONTENTS); final byte[] outc = new byte[(contentsLit.getPosLength() - 2) / 2]; final PdfPKCS7 pkcs7 = sig.getSigner(); pkcs7.setExternalDigest(signature, hash, "RSA"); final PdfDictionary dic = new PdfDictionary(); byte[] ssig = pkcs7.getEncodedPKCS7(); try { // try to retrieve cryptographic timestamp from configured tsa server ssig = pkcs7.getEncodedPKCS7(null, null, new TSAClientBouncyCastle(tsaAddress), null); } catch (final RuntimeException e) { log.error("Could not retrieve timestamp from server.", e); } System.arraycopy(ssig, 0, outc, 0, ssig.length); // add the timestamped signature dic.put(PdfName.CONTENTS, new PdfString(outc).setHexWriting(true)); // finish up sap.close(dic); } catch (final InvalidKeyException e) { throw new RuntimeException("Internal implementation error! No such signature type.", e); } catch (final NoSuchAlgorithmException e) { throw new RuntimeException("Internal implementation error! No such algorithm type.", e); } }
From source file:androidGLUESigner.pdf.PDFSignerEngine.java
License:Open Source License
/** * Prepare the signing of the pdf (siganture appearance, placeholders, sigimage, ..) * @param inputStream the stream to the input pdf file * @param outputStream the stream to the output pdf file * @return hash value with ocsp included * @throws IOException/*w ww . j av a 2s .c o m*/ * @throws DocumentException * @throws GeneralSecurityException */ public byte[] prepareSign(InputStream inputStream, OutputStream outputStream) throws IOException, DocumentException, GeneralSecurityException { PdfReader reader = new PdfReader(inputStream); PdfStamper stp = PdfStamper.createSignature(reader, outputStream, '\0', null, true); PdfSignatureAppearance sap = stp.getSignatureAppearance(); sap.setCrypto(null, getCertificateChain(), null, PdfSignatureAppearance.WINCER_SIGNED); PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED); dic.setReason(siginfo.getSignatureReason()); dic.setLocation(siginfo.getSignatureLocation()); dic.setName(siginfo.getSignatureName()); dic.setDate(new PdfDate(sap.getSignDate())); sap.setCryptoDictionary(dic); // get the selected rectangle and pagenumber for visible signature Rectangle signatureRect = new Rectangle(siginfo.getSignatureRect().left, siginfo.getSignatureRect().bottom, siginfo.getSignatureRect().right, siginfo.getSignatureRect().top); int pageNumber = siginfo.getPageNumber(); sap.setVisibleSignature(signatureRect, pageNumber, null); // set signature picture, if there is one if (siginfo.getSignatureType() == SignatureType.PICTURE) { Image obj_pic = Image.getInstance(siginfo.getImagePath()); sap.setImage(obj_pic); } // preserve some space for the contents HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer>(); exc.put(PdfName.CONTENTS, new Integer(SIGNATURE_MAX_SIZE * 2 + 2)); sap.preClose(exc); // Save placeholder which will be replaced with actual signature later byte[] placeHolder = getPlaceHolderArr(SIGNATURE_MAX_SIZE * 2); // Replace the contents PdfDictionary dic2 = new PdfDictionary(); dic2.put(PdfName.CONTENTS, new PdfString(placeHolder).setHexWriting(true)); sap.close(dic2); // Calculate the digest InputStream data = sap.getRangeStream(); MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); byte buf[] = new byte[8192]; int n; while ((n = data.read(buf)) > 0) { messageDigest.update(buf, 0, n); } hash = messageDigest.digest(); calendar = Calendar.getInstance(); ocsp = ocspRequest(cert, issuerCert); System.out.println("Got OCSP response, length = " + ocsp.length); // Calculate another digest over authenticatedAttributes PdfPKCS7 sgn = new PdfPKCS7(null, getCertificateChain(), null, hashAlgo, null, true); byte[] sh = sgn.getAuthenticatedAttributeBytes(hash, calendar, ocsp); return sh; }
From source file:androidGLUESigner.pdf.PDFSignerEngine.java
License:Open Source License
/** * Simple Sign method to create a signature without Online Timestamp (needed if device * has no internet connection)/*from ww w. j a va 2 s .c o m*/ * * @param inputfile the inputfile * @param outputfile the outpuftile * @param connection the IConnection Object */ public void simpleSign(String inputfile, String outputfile, IConnection connection) throws IOException, DocumentException, CertificateException, InvalidKeyException, NoSuchAlgorithmException, SignatureException, ReaderException { try { SignatureInfo sigInfo = getSiginfo(); PdfReader reader = new PdfReader(inputfile); FileOutputStream fout = new FileOutputStream(outputfile); PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0', null, true); PdfSignatureAppearance sap = stp.getSignatureAppearance(); sap.setCrypto(null, new Certificate[] { getCertificateChain()[0] }, null, PdfSignatureAppearance.SELF_SIGNED); sap.setReason(sigInfo.getSignatureReason()); sap.setLocation(sigInfo.getSignatureLocation()); // get the selected rectangle and pagenumber for visible signature Rectangle signatureRect = new Rectangle(siginfo.getSignatureRect().left, siginfo.getSignatureRect().bottom, siginfo.getSignatureRect().right, siginfo.getSignatureRect().top); int pageNumber = siginfo.getPageNumber(); sap.setVisibleSignature(signatureRect, pageNumber, null); // set signature picture, if there is one if (siginfo.getSignatureType() == SignatureType.PICTURE) { Image obj_pic = Image.getInstance(siginfo.getImagePath()); sap.setImage(obj_pic); } sap.setExternalDigest(new byte[256], new byte[20], null); sap.preClose(); java.io.InputStream inp = sap.getRangeStream(); byte bytesToHash[] = IOUtils.toByteArray(inp); // sign the hash value byte[] signed = connection.sign(bytesToHash); PdfPKCS7 pdfSignature = sap.getSigStandard().getSigner(); pdfSignature.setExternalDigest(signed, null, "RSA"); PdfDictionary dic = new PdfDictionary(); dic.put(PdfName.CONTENTS, new PdfString(pdfSignature.getEncodedPKCS1()).setHexWriting(true)); sap.close(dic); } catch (Exception e) { Logger.toConsole(e); } }
From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java
License:Open Source License
@SuppressWarnings("unchecked") protected static void main(String[] args) throws Exception { byte[] pdf;//from w ww .ja v a2 s .c o m { File f = new File("c:/trabalhos/java/teste.pdf"); FileInputStream fin = new FileInputStream(f); pdf = new byte[(int) f.length()]; fin.read(pdf); fin.close(); } PdfReader reader = new PdfReader(pdf); FileOutputStream fout = new FileOutputStream("c:/trabalhos/java/teste_assinado.pdf"); final int SIZE = 256000; PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0'); PdfSignatureAppearance sap = stp.getSignatureAppearance(); PdfDictionary dic = new PdfDictionary(); dic.put(PdfName.TYPE, PdfName.SIG); dic.put(PdfName.FILTER, new PdfName("Adobe.PPKMS")); dic.put(PdfName.SUBFILTER, new PdfName("adbe.pkcs7.detached")); sap.setCryptoDictionary(dic); HashMap exc = new HashMap(); exc.put(PdfName.CONTENTS, new Integer(SIZE)); sap.setSignDate(Calendar.getInstance()); sap.preClose(exc); byte[] data = streamToByteArray(sap.getRangeStream()); FileOutputStream fout2 = new FileOutputStream("c:/trabalhos/java/teste_hash.b64"); fout2.write(Base64.encode(data).getBytes()); fout2.close(); File f = new File("c:/trabalhos/java/teste_sign.b64"); FileInputStream fin = new FileInputStream(f); byte[] signatureB64 = new byte[(int) f.length()]; fin.read(signatureB64); @SuppressWarnings("unused") StringBuilder sb = new StringBuilder(); byte[] signature1 = Base64.decode(new String(signatureB64)); fin.close(); byte[] A_CP = converterPkcs7EmCMSComCertificadosECRLs(signature1); CMSSignedData A_T = TimeStamper.addTimestamp(new CMSSignedData(A_CP)); // verificarAssinaturaCMS(conteudo, A_T.getEncoded(), dtAssinatura); byte[] signature = A_T.getEncoded(); byte[] outc = new byte[(SIZE - 2) / 2]; System.arraycopy(signature, 0, outc, 0, signature.length); PdfDictionary dic2 = new PdfDictionary(); dic2.put(PdfName.CONTENTS, new PdfString(outc).setHexWriting(true)); sap.close(dic2); }
From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java
License:Open Source License
@SuppressWarnings("unchecked") protected static void addSignatureToPDF(byte[] pdf, byte[] signature) throws Exception { PdfReader reader = new PdfReader(pdf); FileOutputStream fout = new FileOutputStream("c:/trabalhos/java/teste_assinado.pdf"); final int SIZE = 128000; PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0'); PdfSignatureAppearance sap = stp.getSignatureAppearance(); PdfDictionary dic = new PdfDictionary(); dic.put(PdfName.TYPE, PdfName.SIG); dic.put(PdfName.FILTER, new PdfName("Adobe.PPKMS")); dic.put(PdfName.SUBFILTER, new PdfName("adbe.pkcs7.detached")); sap.setCryptoDictionary(dic);/*ww w . java2s .co m*/ HashMap exc = new HashMap(); exc.put(PdfName.CONTENTS, new Integer(SIZE)); sap.preClose(exc); byte[] data = streamToByteArray(sap.getRangeStream()); FileOutputStream fout2 = new FileOutputStream("c:/trabalhos/java/teste_hash.b64"); fout2.write(Base64.encode(data).getBytes()); fout2.close(); File f = new File("c:/trabalhos/java/teste_sign.b64"); FileInputStream fin = new FileInputStream(f); byte[] signatureB64 = new byte[(int) f.length()]; fin.read(signatureB64); @SuppressWarnings("unused") StringBuilder sb = new StringBuilder(); byte[] signature1 = Base64.decode(new String(signatureB64)); fin.close(); byte[] A_CP = converterPkcs7EmCMSComCertificadosECRLs(signature1); CMSSignedData A_T = TimeStamper.addTimestamp(new CMSSignedData(A_CP)); // verificarAssinaturaCMS(conteudo, A_T.getEncoded(), dtAssinatura); signature = A_T.getEncoded(); byte[] outc = new byte[(SIZE - 2) / 2]; System.arraycopy(signature, 0, outc, 0, signature.length); PdfDictionary dic2 = new PdfDictionary(); dic2.put(PdfName.CONTENTS, new PdfString(outc).setHexWriting(true)); sap.close(dic2); }
From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java
License:Open Source License
@SuppressWarnings("unchecked") protected static byte[] getHasheableRangeFromPDF(byte[] pdf) throws Exception { PdfReader reader = new PdfReader(pdf); OutputStream fout = new NullOutputStream(); final int SIZE = 128000; PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0'); PdfSignatureAppearance sap = stp.getSignatureAppearance(); PdfDictionary dic = new PdfDictionary(); dic.put(PdfName.TYPE, PdfName.SIG); dic.put(PdfName.FILTER, new PdfName("Adobe.PPKMS")); dic.put(PdfName.SUBFILTER, new PdfName("adbe.pkcs7.detached")); sap.setCryptoDictionary(dic);/*from w w w . ja v a 2s . c om*/ HashMap exc = new HashMap(); exc.put(PdfName.CONTENTS, new Integer(SIZE)); sap.preClose(exc); byte[] data = streamToByteArray(sap.getRangeStream()); byte[] outc = new byte[(SIZE - 2) / 2]; PdfDictionary dic2 = new PdfDictionary(); dic2.put(PdfName.CONTENTS, new PdfString(outc).setHexWriting(true)); sap.close(dic2); System.out.println("Hash: " + MessageDigest.getInstance("MD5").digest(data, 0, data.length)); return data; }
From source file:classroom.newspaper_b.Newspaper09.java
public static void main(String[] args) { try {/*from ww w .j a va2 s . c om*/ PdfReader reader = new PdfReader(NEWSPAPER); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT)); PdfAnnotation annotation1 = PdfAnnotation.createSquareCircle(stamper.getWriter(), new Rectangle(LLX1, LLY1, URX1, URY1), MESSAGE, true); annotation1.put(PdfName.T, new PdfString("Advertisement 1")); annotation1.put(PdfName.C, new PdfArray(new float[] { 1, 0, 0 })); stamper.addAnnotation(annotation1, 1); PdfAnnotation annotation2 = PdfAnnotation.createText(stamper.getWriter(), new Rectangle(LLX2, LLY2, URX2, URY2), "Advertisement 2", MESSAGE, false, null); annotation2.put(PdfName.NM, new PdfString("ad2")); // the text must be read only, and the annotation set to NOVIEW annotation2.put(PdfName.F, new PdfNumber(PdfAnnotation.FLAGS_READONLY | PdfAnnotation.FLAGS_NOVIEW)); // we create a popup annotation that will define where the rectangle will appear PdfAnnotation popup = PdfAnnotation.createPopup(stamper.getWriter(), new Rectangle(LLX2 + 50, LLY2 + 120, URX2 - 80, URY2 - 120), null, false); // we add a reference to the text annotation to the popup annotation popup.put(PdfName.PARENT, annotation2.getIndirectReference()); // we add a reference to the popup annotation to the text annotation annotation2.put(PdfName.POPUP, popup.getIndirectReference()); // we add both annotations to the writer stamper.addAnnotation(annotation2, 1); stamper.addAnnotation(popup, 1); // the text annotation can't be viewed (it's invisible) // we create a widget annotation named mywidget (it's a button field) PushbuttonField field = new PushbuttonField(stamper.getWriter(), new Rectangle(LLX2, LLY2, URX2, URY2), "button"); PdfAnnotation widget = field.getField(); PdfDictionary dict = new PdfDictionary(); // we write some javascript that makes the popup of the text annotation visible/invisible on mouse enter/exit String js1 = "var t = this.getAnnot(this.pageNum, 'ad2'); t.popupOpen = true; var w = this.getField('button'); w.setFocus();"; PdfAction enter = PdfAction.javaScript(js1, stamper.getWriter()); dict.put(PdfName.E, enter); String js2 = "var t = this.getAnnot(this.pageNum, 'ad2'); t.popupOpen = false;"; PdfAction exit = PdfAction.javaScript(js2, stamper.getWriter()); dict.put(PdfName.X, exit); // we add the javascript as additional action widget.put(PdfName.AA, dict); // we add the button field stamper.addAnnotation(widget, 1); stamper.close(); } catch (IOException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } }
From source file:com.dlya.facturews.DlyaPdfExporter2.java
License:Open Source License
/** * *//*from w w w . ja v a2s . co m*/ protected void exportReportToStream(OutputStream os) throws JRException { //ByteArrayOutputStream baos = new ByteArrayOutputStream(); document = new Document(new Rectangle(jasperPrint.getPageWidth(), jasperPrint.getPageHeight())); imageTesterDocument = new Document(new Rectangle(10, //jasperPrint.getPageWidth(), 10 //jasperPrint.getPageHeight() )); boolean closeDocuments = true; try { pdfWriter = PdfWriter.getInstance(document, os); pdfWriter.setCloseStream(false); if (pdfVersion != null) { pdfWriter.setPdfVersion(pdfVersion.charValue()); } if (isCompressed) { pdfWriter.setFullCompression(); } if (isEncrypted) { pdfWriter.setEncryption(is128BitKey, userPassword, ownerPassword, permissions); } if (printScaling != null) { if (JRPdfExporterParameter.PRINT_SCALING_DEFAULT.equals(printScaling)) { //pdfWriter.addViewerPreference(PdfName.PRINTSCALING, PdfName.APPDEFAULT); } else if (JRPdfExporterParameter.PRINT_SCALING_NONE.equals(printScaling)) { //pdfWriter.addViewerPreference(PdfName.PRINTSCALING, PdfName.NONE); } } // Add meta-data parameters to generated PDF document // mtclough@users.sourceforge.net 2005-12-05 String title = (String) parameters.get(JRPdfExporterParameter.METADATA_TITLE); if (title != null) { document.addTitle(title); } String author = (String) parameters.get(JRPdfExporterParameter.METADATA_AUTHOR); if (author != null) { document.addAuthor(author); } String subject = (String) parameters.get(JRPdfExporterParameter.METADATA_SUBJECT); if (subject != null) { document.addSubject(subject); } String keywords = (String) parameters.get(JRPdfExporterParameter.METADATA_KEYWORDS); if (keywords != null) { document.addKeywords(keywords); } String creator = (String) parameters.get(JRPdfExporterParameter.METADATA_CREATOR); if (creator != null) { document.addCreator(creator); } else { document.addCreator("JasperReports (" + jasperPrint.getName() + ")"); } // BEGIN: PDF/A support String pdfaConformance = getStringParameter(JRPdfExporterParameter.PDFA_CONFORMANCE, JRPdfExporterParameter.PROPERTY_PDFA_CONFORMANCE); boolean gotPdfa = false; if (pdfaConformance != null && !JRPdfExporterParameter.PDFA_CONFORMANCE_NONE.equalsIgnoreCase(pdfaConformance)) { if (JRPdfExporterParameter.PDFA_CONFORMANCE_1A.equalsIgnoreCase(pdfaConformance)) { //pdfWriter.setPDFXConformance(PdfWriter.PDFA1A); gotPdfa = true; } else if (JRPdfExporterParameter.PDFA_CONFORMANCE_1B.equalsIgnoreCase(pdfaConformance)) { //pdfWriter.setPDFXConformance(PdfWriter.PDFA1B); gotPdfa = true; } } if (gotPdfa) { //pdfWriter.createXmpMetadata(); } else { //pdfWriter.setRgbTransparencyBlending(true); } // END: PDF/A support document.open(); // BEGIN: PDF/A support if (gotPdfa) { String iccProfilePath = getStringParameter(JRPdfExporterParameter.PDFA_ICC_PROFILE_PATH, JRPdfExporterParameter.PROPERTY_PDFA_ICC_PROFILE_PATH); if (iccProfilePath != null) { PdfDictionary pdfDictionary = new PdfDictionary(PdfName.OUTPUTINTENT); pdfDictionary.put(PdfName.OUTPUTCONDITIONIDENTIFIER, new PdfString("sRGB IEC61966-2.1")); pdfDictionary.put(PdfName.INFO, new PdfString("sRGB IEC61966-2.1")); //pdfDictionary.put(PdfName.S, PdfName.GTS_PDFA1); InputStream iccIs = RepositoryUtil.getInstance(jasperReportsContext) .getInputStreamFromLocation(iccProfilePath); //PdfICCBased pdfICCBased = new PdfICCBased(ICC_Profile.getInstance(iccIs)); //pdfICCBased.remove(PdfName.ALTERNATE); //pdfDictionary.put(PdfName.DESTOUTPUTPROFILE, pdfWriter.addToBody(pdfICCBased).getIndirectReference()); pdfWriter.getExtraCatalog().put(PdfName.OUTPUTINTENTS, new PdfArray(pdfDictionary)); } else { throw new JRPdfaIccProfileNotFoundException(); } } // END: PDF/A support if (pdfJavaScript != null) { pdfWriter.addJavaScript(pdfJavaScript); } pdfContentByte = pdfWriter.getDirectContent(); //tagHelper.init(pdfContentByte); initBookmarks(); PdfWriter imageTesterPdfWriter = PdfWriter.getInstance(imageTesterDocument, new NullOutputStream() // discard the output ); imageTesterDocument.open(); imageTesterDocument.newPage(); imageTesterPdfContentByte = imageTesterPdfWriter.getDirectContent(); imageTesterPdfContentByte.setLiteral("\n"); for (reportIndex = 0; reportIndex < jasperPrintList.size(); reportIndex++) { setJasperPrint(jasperPrintList.get(reportIndex)); loadedImagesMap = new HashMap<Renderable, com.lowagie.text.Image>(); setPageSize(null); BorderOffset.setLegacy(JRPropertiesUtil.getInstance(jasperReportsContext) .getBooleanProperty(jasperPrint, BorderOffset.PROPERTY_LEGACY_BORDER_OFFSET, false)); boolean sizePageToContent = JRPropertiesUtil.getInstance(jasperReportsContext).getBooleanProperty( jasperPrint, JRPdfExporterParameter.PROPERTY_SIZE_PAGE_TO_CONTENT, false); List<JRPrintPage> pages = jasperPrint.getPages(); if (pages != null && pages.size() > 0) { if (isModeBatch) { document.newPage(); if (isCreatingBatchModeBookmarks) { //add a new level to our outline for this report addBookmark(0, jasperPrint.getName(), 0, 0); } startPageIndex = 0; endPageIndex = pages.size() - 1; } for (int pageIndex = startPageIndex; pageIndex <= endPageIndex; pageIndex++) { if (Thread.interrupted()) { throw new JRException("Current thread interrupted."); } JRPrintPage page = pages.get(pageIndex); if (sizePageToContent) { setPageSize(page); } document.newPage(); pdfContentByte = pdfWriter.getDirectContent(); pdfContentByte.setLineCap(2);//PdfContentByte.LINE_CAP_PROJECTING_SQUARE since iText 1.02b writePageAnchor(pageIndex); /* */ exportPage(page); } } else { document.newPage(); pdfContentByte = pdfWriter.getDirectContent(); pdfContentByte.setLiteral("\n"); } } closeDocuments = false; document.close(); imageTesterDocument.close(); } catch (DocumentException e) { throw new JRException("PDF Document error : " + jasperPrint.getName(), e); } catch (IOException e) { throw new JRException("Error generating PDF report : " + jasperPrint.getName(), e); } finally { if (closeDocuments) //only on exception { try { document.close(); } catch (Exception e) { // ignore, let the original exception propagate } try { imageTesterDocument.close(); } catch (Exception e) { // ignore, let the original exception propagate } } } //return os.toByteArray(); }
From source file:de.thorstenberger.examServer.pdf.signature.SignPdf.java
License:Open Source License
/** * Add a signature and a cryptographic timestamp to a pdf document. See www.ietf.org/rfc/rfc3161.txt. Proves that this * pdf had the current content at the current point in time. * * @param originalPdf/*from w w w . j a va 2 s. co m*/ * @param targetPdf * @param pk * @param certChain * @param revoked * @param tsaAddress * address of a rfc 3161 compatible timestamp server * @param reason * reason for the signature * @param location * location of signing * @param contact * emailaddress of the person who is signing * @throws IOException * @throws DocumentException * @throws SignatureException */ public static void signAndTimestamp(final InputStream originalPdf, final OutputStream targetPdf, final PrivateKey pk, final X509Certificate[] certChain, final CRL[] revoked, final String tsaAddress, final String reason, final String location, final String contact) throws IOException, DocumentException, SignatureException { // only an estimate, depends on the certificates returned by the TSA final int timestampSize = 4400; Security.addProvider(new BouncyCastleProvider()); final PdfReader reader = new PdfReader(originalPdf); final PdfStamper stamper = PdfStamper.createSignature(reader, targetPdf, '\0'); final PdfSignatureAppearance sap = stamper.getSignatureAppearance(); // comment next lines to have an invisible signature sap.setVisibleSignature(new Rectangle(450, 650, 500, 700), 1, null); sap.setLayer2Text(""); final PdfSigGenericPKCS sig = new PdfSigGenericPKCS.PPKMS("BC"); final HashMap<PdfName, Integer> exclusionSizes = new HashMap<PdfName, Integer>(); // some informational fields sig.setReason(reason); sig.setLocation(location); sig.setContact(contact); sig.setName(PdfPKCS7.getSubjectFields(certChain[0]).getField("CN")); sig.setDate(new PdfDate(Calendar.getInstance())); // signing stuff final byte[] digest = new byte[256]; final byte[] rsaData = new byte[20]; sig.setExternalDigest(digest, rsaData, "RSA"); sig.setSignInfo(pk, certChain, revoked); final PdfString contents = (PdfString) sig.get(PdfName.CONTENTS); // *2 to get hex size, +2 for delimiters PdfLiteral contentsLit = new PdfLiteral((contents.toString().length() + timestampSize) * 2 + 2); exclusionSizes.put(PdfName.CONTENTS, new Integer(contentsLit.getPosLength())); sig.put(PdfName.CONTENTS, contentsLit); // certification; will display dialog or blue bar in Acrobat Reader sap.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED); // process all the information set above sap.setCryptoDictionary(sig); sap.preClose(exclusionSizes); // calculate digest (hash) try { final MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); final byte[] buf = new byte[8192]; int n; final InputStream inp = sap.getRangeStream(); while ((n = inp.read(buf)) != -1) { messageDigest.update(buf, 0, n); } final byte[] hash = messageDigest.digest(); // make signature (SHA1 the hash, prepend algorithm ID, pad, and encrypt with RSA) final Signature sign = Signature.getInstance("SHA1withRSA"); sign.initSign(pk); sign.update(hash); final byte[] signature = sign.sign(); // prepare the location of the signature in the target PDF contentsLit = (PdfLiteral) sig.get(PdfName.CONTENTS); final byte[] outc = new byte[(contentsLit.getPosLength() - 2) / 2]; final PdfPKCS7 pkcs7 = sig.getSigner(); pkcs7.setExternalDigest(signature, hash, "RSA"); final PdfDictionary dic = new PdfDictionary(); byte[] ssig = pkcs7.getEncodedPKCS7(); try { // try to retrieve cryptographic timestamp from configured tsa server ssig = pkcs7.getEncodedPKCS7(null, null, new TSAClientBouncyCastle(tsaAddress), null); } catch (final RuntimeException e) { log.error("Could not retrieve timestamp from server.", e); } System.arraycopy(ssig, 0, outc, 0, ssig.length); // add the timestamped signature dic.put(PdfName.CONTENTS, new PdfString(outc).setHexWriting(true)); // finish up sap.close(dic); } catch (final InvalidKeyException e) { throw new RuntimeException("Internal implementation error! No such signature type.", e); } catch (final NoSuchAlgorithmException e) { throw new RuntimeException("Internal implementation error! No such algorithm type.", e); } }
From source file:de.unigoettingen.sub.commons.contentlib.pdflib.PDFManager.java
License:Apache License
/** * Creates the pdf writer.//from w ww .ja v a2s . c o m * * @param out the out * @param writer the writer * @param pdfdoc the pdfdoc * * @return the pdf writer * * @throws PDFManagerException the PDF manager exception */ private PdfWriter createPDFWriter(OutputStream out, Document pdfdoc) throws PDFManagerException { PdfWriter writer = null; try { // open the pdfwriter using the outstream writer = PdfWriter.getInstance(pdfdoc, out); LOGGER.debug("PDFWriter intstantiated"); // register Fonts int numoffonts = FontFactory.registerDirectories(); LOGGER.debug(numoffonts + " fonts found and registered!"); if ((pdfa) && (iccprofile != null)) { // we want to write PDFA, we have to set the PDFX conformance // before we open the writer writer.setPDFXConformance(PdfWriter.PDFA1B); } // open the pdf document to add pages and other content try { pdfdoc.open(); LOGGER.debug("PDFDocument opened"); } catch (Exception e) { throw new PDFManagerException("PdfWriter was opened, but the pdf document couldn't be opened", e); } if ((pdfa) && (iccprofile != null)) { // set the required PDFDictionary which // contains the appropriate ICC profile PdfDictionary pdfdict_out = new PdfDictionary(PdfName.OUTPUTINTENT); // set identifier for ICC profile pdfdict_out.put(PdfName.OUTPUTCONDITIONIDENTIFIER, new PdfString("sRGBIEC61966-2.1")); pdfdict_out.put(PdfName.INFO, new PdfString("sRGB IEC61966-2.1")); pdfdict_out.put(PdfName.S, PdfName.GTS_PDFA1); // PdfICCBased ib = new PdfICCBased(iccprofile); // writer.setOutputIntents("Custom", "PDF/A sRGB", null, "PDF/A // sRGB ICC Profile, sRGB_IEC61966-2-1_withBPC.icc", // colorProfileData); // read icc profile // ICC_Profile icc = ICC_Profile.getInstance(new // FileInputStream("c:\\srgb.profile")); PdfICCBased ib = new PdfICCBased(iccprofile); ib.remove(PdfName.ALTERNATE); PdfIndirectObject pio = writer.addToBody(ib); pdfdict_out.put(PdfName.DESTOUTPUTPROFILE, pio.getIndirectReference()); writer.getExtraCatalog().put(PdfName.OUTPUTINTENTS, new PdfArray(pdfdict_out)); // create MarkInfo elements // not sure this is necessary; maybe just needed for tagged PDFs // (PDF/A 1a) PdfDictionary markInfo = new PdfDictionary(PdfName.MARKINFO); markInfo.put(PdfName.MARKED, new PdfBoolean("false")); writer.getExtraCatalog().put(PdfName.MARKINFO, markInfo); // write XMP this.writeXMPMetadata(writer); } } catch (Exception e) { LOGGER.error("Can't open the PdfWriter object\n" + e.toString() + "\n" + e.getMessage()); throw new PDFManagerException("Can't open the PdfWriter object", e); } return writer; }