List of usage examples for org.apache.pdfbox.cos COSName FILTER
COSName FILTER
To view the source code for org.apache.pdfbox.cos COSName FILTER.
Click Source Link
From source file:ReducePDFSize.java
License:Apache License
public static void main(String[] args) throws IOException { if (2 != args.length) { throw new RuntimeException("arg0 must be input file, org1 must be output file"); }/*from ww w .ja v a 2 s .c o m*/ String in = args[0]; String out = args[1]; PDDocument doc = null; try { doc = PDDocument.load(new File(in)); doc.setAllSecurityToBeRemoved(true); for (COSObject cosObject : doc.getDocument().getObjects()) { COSBase base = cosObject.getObject(); // if it's a stream: decode it, then re-write it using FLATE_DECODE if (base instanceof COSStream) { COSStream stream = (COSStream) base; byte[] bytes; try { bytes = new PDStream(stream).toByteArray(); } catch (IOException ex) { // NOTE: original example code from PDFBox just logged & "continue;"d here, 'skipping' this stream. // If this type of failure ever happens, we can (perhaps) consider (re)ignoring this type of failure? // // IIUC then that will leave the original (non-decoded / non-flated) stream in place? throw new RuntimeException("can't serialize byte[] from: " + cosObject.getObjectNumber() + " " + cosObject.getGenerationNumber() + " obj: " + ex.getMessage(), ex); } stream.removeItem(COSName.FILTER); OutputStream streamOut = stream.createOutputStream(COSName.FLATE_DECODE); streamOut.write(bytes); streamOut.close(); } } doc.getDocumentCatalog(); doc.save(out); } finally { if (doc != null) { doc.close(); } } }
From source file:net.padaf.preflight.helpers.MetadataValidationHelper.java
License:Apache License
/** * Return the xpacket from the dictionary's stream *//*from www .j a va 2s . c o m*/ public static byte[] getXpacket(COSDocument cdocument) throws IOException, XpacketParsingException { COSObject catalog = cdocument.getCatalog(); COSBase cb = catalog.getDictionaryObject(COSName.METADATA); if (cb == null) { // missing Metadata Key in catalog ValidationError error = new ValidationError(ValidationConstants.ERROR_METADATA_FORMAT, "Missing Metadata Key in catalog"); throw new XpacketParsingException("Failed while retrieving xpacket", error); } // no filter key COSDictionary metadataDictionnary = COSUtils.getAsDictionary(cb, cdocument); if (metadataDictionnary.getItem(COSName.FILTER) != null) { // should not be defined ValidationError error = new ValidationError(ValidationConstants.ERROR_SYNTAX_STREAM_INVALID_FILTER, "Filter specified in metadata dictionnary"); throw new XpacketParsingException("Failed while retrieving xpacket", error); } PDStream stream = PDStream.createFromCOS(metadataDictionnary); ByteArrayOutputStream bos = new ByteArrayOutputStream(); InputStream is = stream.createInputStream(); IOUtils.copy(is, bos); is.close(); bos.close(); return bos.toByteArray(); }
From source file:org.apache.fop.render.pdf.pdfbox.PDFBoxAdapter.java
License:Apache License
private Object readCOSStream(COSStream originalStream, Object keyBase) throws IOException { InputStream in;/*w w w. j a v a 2 s. co m*/ Set filter; if (pdfDoc.isEncryptionActive() || (originalStream.containsKey(COSName.DECODE_PARMS) && !originalStream.containsKey(COSName.FILTER))) { in = originalStream.getUnfilteredStream(); filter = FILTER_FILTER; } else { //transfer encoded data (don't reencode) in = originalStream.getFilteredStream(); filter = Collections.EMPTY_SET; } PDFStream stream = new PDFStream(); OutputStream out = stream.getBufferOutputStream(); IOUtils.copyLarge(in, out); transferDict(originalStream, stream, filter); return cacheClonedObject(keyBase, stream); }
From source file:org.apache.fop.render.pdf.pdfbox.PDFBoxAdapter.java
License:Apache License
private void mergeXObj(COSDictionary sourcePageResources, FontInfo fontinfo, UniqueName uniqueName) throws IOException { COSDictionary xobj = (COSDictionary) sourcePageResources.getDictionaryObject(COSName.XOBJECT); if (xobj != null && pdfDoc.isMergeFontsEnabled()) { for (Map.Entry<COSName, COSBase> i : xobj.entrySet()) { COSObject v = (COSObject) i.getValue(); COSStream stream = (COSStream) v.getObject(); COSDictionary res = (COSDictionary) stream.getDictionaryObject(COSName.RESOURCES); if (res != null) { COSDictionary src = (COSDictionary) res.getDictionaryObject(COSName.FONT); if (src != null) { COSDictionary target = (COSDictionary) sourcePageResources .getDictionaryObject(COSName.FONT); if (target == null) { sourcePageResources.setItem(COSName.FONT, src); } else { for (Map.Entry<COSName, COSBase> entry : src.entrySet()) { if (!target.keySet().contains(entry.getKey())) { target.setItem(uniqueName.getName(entry.getKey()), entry.getValue()); }/*ww w .ja va 2 s .c om*/ } } PDFWriter writer = new MergeFontsPDFWriter(src, fontinfo, uniqueName, parentFonts, 0); String c = writer.writeText(new PDStream(stream)); if (c != null) { stream.removeItem(COSName.FILTER); newXObj.put(i.getKey(), c); for (Object e : src.keySet().toArray()) { COSName name = (COSName) e; src.setItem(uniqueName.getName(name), src.getItem(name)); src.removeItem(name); } } } } } } }
From source file:pdfpicmangler.PDPng.java
License:Open Source License
/** * Construct from a stream./*w w w . j a v a 2 s . com*/ * * @param doc The document to create the image as part of. * @param is The stream that contains the png data. * @throws IOException If there is an error reading the png data. */ public PDPng(PDDocument doc, InputStream is) throws IOException { super(doc, "png"); System.out.println("reading in png"); COSDictionary dic = getCOSStream(); dic.setItem(COSName.SUBTYPE, COSName.IMAGE); //dic.setItem(COSName.TYPE, COSName.XOBJECT); data = getCOSStream().createFilteredStream(); readPng(is); setWidth(imageWidth); setHeight(imageHeight); dic.setInt(COSName.BITS_PER_COMPONENT, bitDepth); if ((colorType & PNG_TYPE_PALETTE) != 0) { getCOSStream().setItem(COSName.COLORSPACE, paldata); } else if ((colorType & PNG_TYPE_COLOR) != 0) { setColorSpace(PDDeviceRGB.INSTANCE); } else { setColorSpace(new PDDeviceGray()); } COSDictionary filterParams = new COSDictionary(); filterParams.setInt(COSName.PREDICTOR, 15); // png adaptive predictor filterParams.setInt(COSName.COLORS, ((colorType & PNG_TYPE_COLOR) == 0 || (colorType & PNG_TYPE_PALETTE) != 0) ? 1 : 3); filterParams.setInt(COSName.BITS_PER_COMPONENT, bitDepth); filterParams.setInt(COSName.COLUMNS, imageWidth); filterParams.setDirect(true); dic.setItem(COSName.DECODE_PARMS, filterParams); dic.setItem(COSName.FILTER, COSName.FLATE_DECODE); dic.setInt(COSName.LENGTH, dataLen); dic.getDictionaryObject(COSName.LENGTH).setDirect(true); }
From source file:test.be.fedict.eid.applet.PdfSpikeTest.java
License:Open Source License
@Test public void testSignPDF() throws Exception { // create a sample PDF file Document document = new Document(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter.getInstance(document, baos); document.open();/* www . j a va 2 s . co m*/ Paragraph titleParagraph = new Paragraph("This is a test."); titleParagraph.setAlignment(Paragraph.ALIGN_CENTER); document.add(titleParagraph); document.newPage(); Paragraph textParagraph = new Paragraph("Hello world."); document.add(textParagraph); document.close(); File tmpFile = File.createTempFile("test-", ".pdf"); LOG.debug("tmp file: " + tmpFile.getAbsolutePath()); FileUtils.writeByteArrayToFile(tmpFile, baos.toByteArray()); // eID PcscEid pcscEid = new PcscEid(new TestView(), new Messages(Locale.getDefault())); if (false == pcscEid.isEidPresent()) { LOG.debug("insert eID card"); pcscEid.waitForEidPresent(); } List<X509Certificate> signCertificateChain = pcscEid.getSignCertificateChain(); Certificate[] certs = new Certificate[signCertificateChain.size()]; for (int idx = 0; idx < certs.length; idx++) { certs[idx] = signCertificateChain.get(idx); } // open the pdf FileInputStream pdfInputStream = new FileInputStream(tmpFile); File signedTmpFile = File.createTempFile("test-signed-", ".pdf"); PdfReader reader = new PdfReader(pdfInputStream); FileOutputStream pdfOutputStream = new FileOutputStream(signedTmpFile); PdfStamper stamper = PdfStamper.createSignature(reader, pdfOutputStream, '\0', null, true); // add extra page Rectangle pageSize = reader.getPageSize(1); int pageCount = reader.getNumberOfPages(); int extraPageIndex = pageCount + 1; stamper.insertPage(extraPageIndex, pageSize); // calculate unique signature field name int signatureNameIndex = 1; String signatureName; AcroFields existingAcroFields = reader.getAcroFields(); List<String> existingSignatureNames = existingAcroFields.getSignatureNames(); do { signatureName = "Signature" + signatureNameIndex; signatureNameIndex++; } while (existingSignatureNames.contains(signatureName)); LOG.debug("new unique signature name: " + signatureName); PdfSignatureAppearance signatureAppearance = stamper.getSignatureAppearance(); signatureAppearance.setCrypto(null, certs, null, PdfSignatureAppearance.SELF_SIGNED); signatureAppearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED); signatureAppearance.setReason("PDF Signature Test"); signatureAppearance.setLocation("Belgium"); signatureAppearance.setVisibleSignature(new Rectangle(54, 440, 234, 566), extraPageIndex, signatureName); signatureAppearance.setExternalDigest(new byte[128], new byte[20], "RSA"); signatureAppearance.preClose(); byte[] content = IOUtils.toByteArray(signatureAppearance.getRangeStream()); byte[] hash = MessageDigest.getInstance("SHA-1").digest(content); byte[] signatureBytes = pcscEid.sign(hash, "SHA-1"); pcscEid.close(); PdfSigGenericPKCS sigStandard = signatureAppearance.getSigStandard(); PdfPKCS7 signature = sigStandard.getSigner(); signature.setExternalDigest(signatureBytes, hash, "RSA"); PdfDictionary dictionary = new PdfDictionary(); dictionary.put(PdfName.CONTENTS, new PdfString(signature.getEncodedPKCS1()).setHexWriting(true)); signatureAppearance.close(dictionary); LOG.debug("signed tmp file: " + signedTmpFile.getAbsolutePath()); // verify the signature reader = new PdfReader(new FileInputStream(signedTmpFile)); AcroFields acroFields = reader.getAcroFields(); ArrayList<String> signatureNames = acroFields.getSignatureNames(); for (String signName : signatureNames) { LOG.debug("signature name: " + signName); LOG.debug("signature covers whole document: " + acroFields.signatureCoversWholeDocument(signName)); LOG.debug("document revision " + acroFields.getRevision(signName) + " of " + acroFields.getTotalRevisions()); PdfPKCS7 pkcs7 = acroFields.verifySignature(signName); Calendar signDate = pkcs7.getSignDate(); LOG.debug("signing date: " + signDate.getTime()); LOG.debug("Subject: " + PdfPKCS7.getSubjectFields(pkcs7.getSigningCertificate())); LOG.debug("Document modified: " + !pkcs7.verify()); Certificate[] verifyCerts = pkcs7.getCertificates(); for (Certificate certificate : verifyCerts) { X509Certificate x509Certificate = (X509Certificate) certificate; LOG.debug("cert subject: " + x509Certificate.getSubjectX500Principal()); } } /* * Reading the signature using Apache PDFBox. */ PDDocument pdDocument = PDDocument.load(signedTmpFile); COSDictionary trailer = pdDocument.getDocument().getTrailer(); /* * PDF Reference - third edition - Adobe Portable Document Format - * Version 1.4 - 3.6.1 Document Catalog */ COSDictionary documentCatalog = (COSDictionary) trailer.getDictionaryObject(COSName.ROOT); /* * 8.6.1 Interactive Form Dictionary */ COSDictionary acroForm = (COSDictionary) documentCatalog.getDictionaryObject(COSName.ACRO_FORM); COSArray fields = (COSArray) acroForm.getDictionaryObject(COSName.FIELDS); for (int fieldIdx = 0; fieldIdx < fields.size(); fieldIdx++) { COSDictionary field = (COSDictionary) fields.getObject(fieldIdx); String fieldType = field.getNameAsString("FT"); if ("Sig".equals(fieldType)) { COSDictionary signatureDictionary = (COSDictionary) field.getDictionaryObject(COSName.V); /* * TABLE 8.60 Entries in a signature dictionary */ COSString signatoryName = (COSString) signatureDictionary.getDictionaryObject(COSName.NAME); if (null != signatoryName) { LOG.debug("signatory name: " + signatoryName.getString()); } COSString reason = (COSString) signatureDictionary.getDictionaryObject(COSName.REASON); if (null != reason) { LOG.debug("reason: " + reason.getString()); } COSString location = (COSString) signatureDictionary.getDictionaryObject(COSName.LOCATION); if (null != location) { LOG.debug("location: " + location.getString()); } Calendar signingTime = signatureDictionary.getDate(COSName.M); if (null != signingTime) { LOG.debug("signing time: " + signingTime.getTime()); } String signatureHandler = signatureDictionary.getNameAsString(COSName.FILTER); LOG.debug("signature handler: " + signatureHandler); } } }