/** * Extracts document level attachments * * @param filename a file from which document level attachments will be extracted * @throws IOException */ public void extractDocLevelAttachments(String filename) throws IOException { PdfReader reader = new PdfReader(filename); PdfDictionary root = reader.getCatalog(); PdfDictionary documentnames = root.getAsDict(PdfName.NAMES); PdfDictionary embeddedfiles = documentnames.getAsDict(PdfName.EMBEDDEDFILES); PdfArray filespecs = embeddedfiles.getAsArray(PdfName.NAMES); PdfDictionary filespec; PdfDictionary refs; FileOutputStream fos; PRStream stream; for (int i = 0; i < filespecs.size(); ) { filespecs.getAsString(i++); filespec = filespecs.getAsDict(i++); refs = filespec.getAsDict(PdfName.EF); for (PdfName key : refs.getKeys()) { fos = new FileOutputStream(String.format(PATH, filespec.getAsString(key).toString())); stream = (PRStream) PdfReader.getPdfObject(refs.getAsIndirectObject(key)); fos.write(PdfReader.getStreamBytes(stream)); fos.flush(); fos.close(); } } reader.close(); }
private static void merge(String output, Collection<Path> all) { try { Document document = new Document(); PdfCopy copy = new PdfCopy(document, new FileOutputStream(output)); document.open(); PdfReader reader; int n; for (Path pathTemp : all) { if (pathTemp.toFile().getAbsolutePath().endsWith(".pdf")) { reader = new PdfReader(pathTemp.toFile().getAbsolutePath()); n = reader.getNumberOfPages(); for (int page = 0; page < n; ) { copy.addPage(copy.getImportedPage(reader, ++page)); } copy.freeReader(reader); reader.close(); } } document.close(); } catch (Exception e) { System.out.println(e); } }
// FIXME: Manage Exceptions private OutputStream marcarReporteProgramaRechazado(final Programa programa, InputStream src) throws IOException, DocumentException { PdfReader reader = null; reader = new PdfReader(src); int n = reader.getNumberOfPages(); ByteArrayOutputStream os = new ByteArrayOutputStream(); PdfStamper stamper = null; stamper = new PdfStamper(reader, os); // text watermark Font f = new Font(Font.FontFamily.HELVETICA, 65); Phrase p = new Phrase("RECHAZADO", f); // transparency PdfGState gs1 = new PdfGState(); gs1.setFillOpacity(0.3f); // properties PdfContentByte over; Rectangle pagesize; float x, y; // loop over every page for (int i = 1; i <= n; i++) { pagesize = reader.getPageSizeWithRotation(i); x = (pagesize.getLeft() + pagesize.getRight()) / 2; y = (pagesize.getTop() + pagesize.getBottom()) / 2; over = stamper.getOverContent(i); over.saveState(); over.setGState(gs1); ColumnText.showTextAligned(over, Element.ALIGN_CENTER, p, x, y, 45); } stamper.close(); reader.close(); return os; }
private static void concatPDFs(List<String> pdfs, OutputStream outputStream, String tempDiv) { ByteArrayOutputStream byteStream = null; Document document = new Document(); try { PdfCopy copy = new PdfCopy(document, outputStream); document.open(); for (String pdf : pdfs) { String fileLocation = tempDiv + pdf; InputStream templateIs = new FileInputStream(fileLocation); PdfReader reader = new PdfReader(templateIs); byteStream = new ByteArrayOutputStream(); PdfStamper stamper = new PdfStamper(reader, byteStream); stamper.setFreeTextFlattening(true); stamper.setFormFlattening(true); stamper.close(); PdfReader pdfReader = new PdfReader(byteStream.toByteArray()); for (int page = 0; page < pdfReader.getNumberOfPages(); ) { copy.addPage(copy.getImportedPage(pdfReader, ++page)); } pdfReader.close(); reader.close(); } document.close(); copy.close(); } catch (Exception e) { logger.error(e, e); } finally { if (document.isOpen()) document.close(); try { if (outputStream != null) outputStream.close(); } catch (IOException ioe) { logger.error(ioe, ioe); } } }
public static void main_2(String[] args) throws IOException, DocumentException { PdfReader reader = new PdfReader(iconFile.getAbsolutePath()); for (int i = 0; i < reader.getXrefSize(); i++) { PdfObject pdfobj = reader.getPdfObject(i); if (pdfobj == null || !pdfobj.isStream()) { continue; } PdfStream stream = (PdfStream) pdfobj; PdfObject pdfsubtype = stream.get(PdfName.SUBTYPE); if (pdfsubtype != null && pdfsubtype.toString().equals(PdfName.IMAGE.toString())) { System.out.println(stream); byte[] imgData = PdfReader.getStreamBytesRaw((PRStream) stream); System.out.println(Hex.encodeHex(imgData)); } } }
public static void main(String[] args) { SearchClientServiceImpl client = new SearchClientServiceImpl(); try { PdfReader reader = new PdfReader("c:\\tools\\files\\rezolutie.pdf"); PdfReaderContentParser parser = new PdfReaderContentParser(reader); TextExtractionStrategy strategy; for (int i = 1; i <= reader.getNumberOfPages(); i++) { strategy = parser.processContent(i, new SimpleTextExtractionStrategy()); String it = strategy.getResultantText(); if (it != null && !it.trim().isEmpty()) { System.out.println(it); DocumentVersions doc = new DocumentVersions(); doc.setContent(it); doc.setTitle("Han7"); doc.setDescription("Descriere"); doc.setData(new Date()); ObjectMapper mapper = new ObjectMapper(); String val = mapper.writeValueAsString(doc); client .getClient() .prepareIndex("twitter", "tweet", String.valueOf(i++)) .setSource(val) .get(); } } reader.close(); } catch (IOException e) { e.printStackTrace(); } finally { client.getClient().close(); } }
/** * Creates a PDF document. * * @param filename the path to the new PDF document * @throws DocumentException * @throws IOException */ public void createPdf(String filename) throws IOException, DocumentException { // step 1 Rectangle rect = new Rectangle(-595, -842, 595, 842); Document document = new Document(rect); // step 2 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename)); // step 3 document.open(); // step 4 // draw the coordinate system PdfContentByte canvas = writer.getDirectContent(); canvas.moveTo(-595, 0); canvas.lineTo(595, 0); canvas.moveTo(0, -842); canvas.lineTo(0, 842); canvas.stroke(); // read the PDF with the logo PdfReader reader = new PdfReader(RESOURCE); PdfTemplate template = writer.getImportedPage(reader, 1); // add it at different positions using different transformations canvas.addTemplate(template, 0, 0); canvas.addTemplate(template, 0.5f, 0, 0, 0.5f, -595, 0); canvas.addTemplate(template, 0.5f, 0, 0, 0.5f, -297.5f, 297.5f); canvas.addTemplate(template, 1, 0, 0.4f, 1, -750, -650); canvas.addTemplate(template, 0, -1, -1, 0, 650, 0); canvas.addTemplate(template, 0, -0.2f, -0.5f, 0, 350, 0); // step 5 document.close(); reader.close(); }
private static void booklet(String input) throws Exception { String output = input.replace(".pdf", "-booklet.pdf"); PdfReader reader = new PdfReader(input); int n = reader.getNumberOfPages(); Rectangle pageSize = reader.getPageSize(1); System.out.println("Input page size: " + pageSize); Document doc = new Document(PageSize.A4.rotate(), 0, 0, 0, 0); PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(output)); doc.open(); splitLine(doc, writer); int[] pages = new int[(n + 3) / 4 * 4]; int x = 1, y = pages.length; for (int i = 0; i < pages.length; ) { pages[i++] = y--; pages[i++] = x++; pages[i++] = x++; pages[i++] = y--; } PdfContentByte cb = writer.getDirectContent(); float bottom = (doc.top() - pageSize.getHeight()) / 2 + kOffset; float left = doc.right() / 2 - (pageSize.getWidth() + kTextWidth) / 2 - kMargin; float right = doc.right() / 2 - (pageSize.getWidth() - kTextWidth) / 2 + kMargin; for (int i = 0; i < pages.length; ) { PdfImportedPage page = getPage(writer, reader, pages[i++]); if (page != null) cb.addTemplate(page, left, bottom); page = getPage(writer, reader, pages[i++]); if (page != null) cb.addTemplate(page, right, bottom); doc.newPage(); } doc.close(); }
/** * Manipulates a PDF file src with the file dest as result * * @param src the original PDF * @param dest the resulting PDF * @throws IOException * @throws DocumentException * @throws SQLException */ public void manipulatePdf(String src, String dest) throws IOException, DocumentException, SQLException { // Create a database connection DatabaseConnection connection = new HsqldbConnection("filmfestival"); // Create a list with bookmarks ArrayList<HashMap<String, Object>> outlines = new ArrayList<HashMap<String, Object>>(); HashMap<String, Object> map = new HashMap<String, Object>(); outlines.add(map); map.put("Title", "Calendar"); ArrayList<HashMap<String, Object>> kids = new ArrayList<HashMap<String, Object>>(); map.put("Kids", kids); int page = 1; List<Date> days = PojoFactory.getDays(connection); for (Date day : days) { HashMap<String, Object> kid = new HashMap<String, Object>(); kids.add(kid); kid.put("Title", day.toString()); kid.put("Action", "GoTo"); kid.put("Page", String.format("%d Fit", page++)); } // Create a reader PdfReader reader = new PdfReader(src); // Create a stamper PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest)); stamper.setOutlines(outlines); // Close the stamper stamper.close(); reader.close(); // Close the database connection connection.close(); }
/** * Switches to the previous revision. * * @throws IOException * @throws GeneralSecurityException */ public void switchToPreviousRevision() throws IOException, GeneralSecurityException { LOGGER.info("Switching to previous revision."); latestRevision = false; dss = reader.getCatalog().getAsDict(PdfName.DSS); Calendar cal = pkcs7.getTimeStampDate(); if (cal == null) cal = pkcs7.getSignDate(); // TODO: get date from signature signDate = cal.getTime(); List<String> names = fields.getSignatureNames(); if (names.size() > 1) { signatureName = names.get(names.size() - 2); reader = new PdfReader(fields.extractRevision(signatureName)); this.fields = reader.getAcroFields(); names = fields.getSignatureNames(); signatureName = names.get(names.size() - 1); pkcs7 = coversWholeDocument(); LOGGER.info( String.format( "Checking %ssignature %s", pkcs7.isTsp() ? "document-level timestamp " : "", signatureName)); } else { LOGGER.info("No signatures in revision"); pkcs7 = null; } }
/** @see com.lowagie.tools.AbstractTool#execute() */ public static void execute(String srcvalue, String destvalue, String rotvalue) { try { if (StringUtils.isBlank(srcvalue)) { throw new InstantiationException("You need to choose a sourcefile"); } File src = new File(srcvalue); if (StringUtils.isBlank(destvalue)) { throw new InstantiationException("You need to choose a destination file"); } File dest = new File(destvalue); if (StringUtils.isBlank(rotvalue)) { throw new InstantiationException("You need to choose a rotation"); } int rotation = Integer.parseInt(rotvalue); // we create a reader for a certain document PdfReader reader = new PdfReader(src.getAbsolutePath()); // we retrieve the total number of pages and the page size int total = reader.getNumberOfPages(); System.out.println("There are " + total + " pages in the original file."); PdfDictionary pageDict; int currentRotation; for (int p = 1; p <= total; p++) { currentRotation = reader.getPageRotation(p); pageDict = reader.getPageN(p); pageDict.put(PdfName.ROTATE, new PdfNumber(currentRotation + rotation)); } PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest)); stamper.close(); } catch (Exception e) { e.printStackTrace(); } }
/** * Parses a PDF and extracts all the images. * * @param src the source PDF * @param dest the resulting PDF */ public void extractImages(String filename) throws IOException, DocumentException { PdfReader reader = new PdfReader(filename); PdfReaderContentParser parser = new PdfReaderContentParser(reader); MyImageRenderListener listener = new MyImageRenderListener(RESULT); for (int i = 1; i <= reader.getNumberOfPages(); i++) { parser.processContent(i, listener); } }
public static ByteArrayOutputStream requestsToPdf( String globalTitle, Date generationDate, ScrambleRequest[] scrambleRequests, String password) throws DocumentException, IOException { Document doc = new Document(); ByteArrayOutputStream totalPdfOutput = new ByteArrayOutputStream(); PdfSmartCopy totalPdfWriter = new PdfSmartCopy(doc, totalPdfOutput); if (password != null) { totalPdfWriter.setEncryption( password.getBytes(), password.getBytes(), PdfWriter.ALLOW_PRINTING, PdfWriter.STANDARD_ENCRYPTION_128); } doc.open(); PdfContentByte cb = totalPdfWriter.getDirectContent(); PdfOutline root = cb.getRootOutline(); HashMap<String, PdfOutline> outlineByPuzzle = new HashMap<String, PdfOutline>(); boolean expandPuzzleLinks = false; int pages = 1; for (int i = 0; i < scrambleRequests.length; i++) { ScrambleRequest scrambleRequest = scrambleRequests[i]; String shortName = scrambleRequest.scrambler.getShortName(); PdfOutline puzzleLink = outlineByPuzzle.get(shortName); if (puzzleLink == null) { PdfDestination d = new PdfDestination(PdfDestination.FIT); puzzleLink = new PdfOutline( root, PdfAction.gotoLocalPage(pages, d, totalPdfWriter), scrambleRequest.scrambler.getLongName(), expandPuzzleLinks); outlineByPuzzle.put(shortName, puzzleLink); } PdfDestination d = new PdfDestination(PdfDestination.FIT); new PdfOutline( puzzleLink, PdfAction.gotoLocalPage(pages, d, totalPdfWriter), scrambleRequest.title); PdfReader pdfReader = createPdf(globalTitle, generationDate, scrambleRequest); for (int j = 0; j < scrambleRequest.copies; j++) { for (int pageN = 1; pageN <= pdfReader.getNumberOfPages(); pageN++) { PdfImportedPage page = totalPdfWriter.getImportedPage(pdfReader, pageN); totalPdfWriter.addPage(page); pages++; } } } doc.close(); return totalPdfOutput; }
public static int getPageCount(File pdf) throws IOException { PdfReader reader = new PdfReader(pdf.getAbsolutePath()); try { return reader.getNumberOfPages(); } finally { if (reader != null) { reader.close(); } } }
/** * Parses a PDF to a plain text file. * * @param pdf the original PDF * @param txt the resulting text * @throws IOException */ public void parsePdf(String pdf, String txt) throws IOException { PdfReader reader = new PdfReader(pdf); PdfReaderContentParser parser = new PdfReaderContentParser(reader); PrintWriter out = new PrintWriter(new FileOutputStream(txt)); TextExtractionStrategy strategy; for (int i = 1; i <= reader.getNumberOfPages(); i++) { strategy = parser.processContent(i, new SimpleTextExtractionStrategy()); out.println(strategy.getResultantText()); } out.flush(); out.close(); }
private String extractTextFromPdf(byte pdfAsByteArray[]) throws IOException, IOException { PdfReader reader = new PdfReader(pdfAsByteArray); TextRenderListener listener = new TextRenderListener(); PdfContentStreamProcessor processor = new PdfContentStreamProcessor(listener); PdfDictionary pageDic = reader.getPageN(1); PdfDictionary resourcesDic = pageDic.getAsDict(PdfName.RESOURCES); byte array[] = ContentByteUtils.getContentBytesForPage(reader, 1); processor.processContent(array, resourcesDic); return listener.getSb(); }
/** * Parses a specific area of a PDF to a plain text file. * * @param pdf the original PDF * @param txt the resulting text * @throws IOException */ public void parsePdf(String pdf, String txt) throws IOException { PdfReader reader = new PdfReader(pdf); PrintWriter out = new PrintWriter(new FileOutputStream(txt)); Rectangle rect = new Rectangle(70, 80, 490, 580); RenderFilter filter = new RegionTextRenderFilter(rect); TextExtractionStrategy strategy; for (int i = 1; i <= reader.getNumberOfPages(); i++) { strategy = new FilteredTextRenderListener(new LocationTextExtractionStrategy(), filter); out.println(PdfTextExtractor.getTextFromPage(reader, i, strategy)); } out.flush(); out.close(); }
public List<Contacts> readContacts(ContactsInitializer contactsInitializer) { Properties properties; String pdfinput; String contents; String[] content; String[] contact; int no_of_pages; int page_no = ApplicationConstants.TWO; PdfReader reader = null; try { properties = contactsInitializer.getProperties(); pdfinput = properties.getProperty(ApplicationConstants.PDF_INPUT); reader = new PdfReader(pdfinput); contents = PdfTextExtractor.getTextFromPage(reader, ApplicationConstants.ONE); content = contents.split(ApplicationConstants.NEW_LINE, ApplicationConstants.TWO); contact = content[1].split(ApplicationConstants.NEW_LINE); genarateContacts(contact); no_of_pages = reader.getNumberOfPages(); while (page_no <= no_of_pages) { contents = PdfTextExtractor.getTextFromPage(reader, page_no); contact = contents.split(ApplicationConstants.NEW_LINE); genarateContacts(contact); page_no++; } logger.info(list.size() + " contacts added to list from pdf file successfully !"); System.out.println(list.size() + " contacts added to list from pdf file successfully !"); } catch (Exception exception) { System.out.println("contacts not created !"); logger.error("contacts not created !"); logger.error(exception); exception.printStackTrace(); } finally { if (reader != null) { try { reader.close(); logger.debug(LoggerConstants.RESOURCES_RELEASED); } catch (Exception exception) { logger.error(exception); exception.printStackTrace(); } } } return list; }
/** * Searches for a tag in a page. * * @param tag the name of the tag * @param object an identifier to find the marked content * @param page a page dictionary * @throws IOException */ public void parseTag(String tag, PdfObject object, PdfDictionary page) throws IOException { PRStream stream = (PRStream) page.getAsStream(PdfName.CONTENTS); // if the identifier is a number, we can extract the content right away if (object instanceof PdfNumber) { PdfNumber mcid = (PdfNumber) object; RenderFilter filter = new MarkedContentRenderFilter(mcid.intValue()); TextExtractionStrategy strategy = new SimpleTextExtractionStrategy(); FilteredTextRenderListener listener = new FilteredTextRenderListener(strategy, filter); PdfContentStreamProcessor processor = new PdfContentStreamProcessor(listener); processor.processContent(PdfReader.getStreamBytes(stream), page.getAsDict(PdfName.RESOURCES)); out.print(SimpleXMLParser.escapeXML(listener.getResultantText(), true)); } // if the identifier is an array, we call the parseTag method // recursively else if (object instanceof PdfArray) { PdfArray arr = (PdfArray) object; int n = arr.size(); for (int i = 0; i < n; i++) { parseTag(tag, arr.getPdfObject(i), page); if (i < n - 1) out.println(); } } // if the identifier is a dictionary, we get the resources from the // dictionary else if (object instanceof PdfDictionary) { PdfDictionary mcr = (PdfDictionary) object; parseTag(tag, mcr.getDirectObject(PdfName.MCID), mcr.getAsDict(PdfName.PG)); } }
public void getContents() throws IOException { fileContents = ""; for (int i = 1; i <= reader.getNumberOfPages(); i++) { strategy = parser.processContent(i, new SimpleTextExtractionStrategy()); fileContents += strategy.getResultantText(); } }
private void readFile(File file) throws IOException { FileInputStream inputStream = new FileInputStream(file); PdfReader reader = new PdfReader(inputStream); int numberOfPages = reader.getNumberOfPages(); for (int page = 1; page <= numberOfPages; page++) { String pageContent = PdfTextExtractor.getTextFromPage(reader, page); List<String> lines = new ArrayList<>(Arrays.asList(pageContent.split("\n"))); for (String line : lines) { if (line.matches("^\\d{2}\\.\\d{2}\\.\\d{4}.+")) { parseLine(line); } } } }
private File convertPdfToPdfA(final InputStream source) throws IOException, DocumentException { final File pdfAFile = TempFileProvider.createTempFile("digitalSigning-" + System.currentTimeMillis(), ".pdf"); // Reads a PDF document. PdfReader reader = new PdfReader(source); // PdfStamper: Applies extra content to the pages of a PDF document. This extra content can be // all the objects allowed in // PdfContentByte including pages from other Pdfs. PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(pdfAFile)); // A generic Document class. Document document = new Document(); // we create a writer that listens to the document PdfWriter writer = stamper.getWriter(); int numberPages = reader.getNumberOfPages(); writer.setPDFXConformance(PdfWriter.PDFA1A); document.open(); // PdfDictionary:A dictionary is an associative table containing pairs of objects. // The first element of each pair is called the key and the second element is called the value // <CODE>PdfName</CODE> is an object that can be used as a name in a PDF-file PdfDictionary outi = new PdfDictionary(PdfName.OUTPUTINTENT); outi.put(PdfName.OUTPUTCONDITIONIDENTIFIER, new PdfString("sRGB IEC61966-2.1")); outi.put(PdfName.INFO, new PdfString("sRGB IEC61966-2.1")); outi.put(PdfName.S, PdfName.GTS_PDFA1); writer.getExtraCatalog().put(PdfName.OUTPUTINTENTS, new PdfArray(outi)); // Add pages PdfImportedPage p = null; Image image; for (int i = 0; i < numberPages; i++) { p = writer.getImportedPage(reader, i + 1); image = Image.getInstance(p); document.add(image); } writer.createXmpMetadata(); document.close(); // Add Metadata from source pdf HashMap<String, String> info = reader.getInfo(); stamper.setMoreInfo(info); stamper.close(); return pdfAFile; }
private static void crop(String input) throws Exception { String output = input.replace(".pdf", "-crop.pdf"); PdfReader reader = new PdfReader(input); final int n = reader.getNumberOfPages(); Rectangle pageSize = reader.getPageSize(1); System.out.println("Input page size: " + pageSize); float left = (pageSize.getWidth() - kTextWidth) / 2 - kMargin; float right = pageSize.getWidth() - left; float bottom = (pageSize.getHeight() - kTextHeight) / 2; float top = pageSize.getHeight() - bottom; PdfRectangle rect = new PdfRectangle(left, bottom + kOffset, right, top + kOffset); for (int i = 1; i <= n; i++) { PdfDictionary pageDict = reader.getPageN(i); pageDict.put(PdfName.CROPBOX, rect); } PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(output)); stamper.close(); }
/** * Processes content from the specified page number using the specified listener * * @param <E> the type of the renderListener - this makes it easy to chain calls * @param pageNumber the page number to process * @param renderListener the listener that will receive render callbacks * @return the provided renderListener * @throws IOException if operations on the reader fail */ public <E extends RenderListener> E processContent(int pageNumber, E renderListener) throws IOException { PdfDictionary pageDic = reader.getPageN(pageNumber); PdfDictionary resourcesDic = pageDic.getAsDict(PdfName.RESOURCES); PdfContentStreamProcessor processor = new PdfContentStreamProcessor(renderListener); processor.processContent( ContentByteUtils.getContentBytesForPage(reader, pageNumber), resourcesDic); return renderListener; }
@Override public void postProcess(ITextContext context, File fileIn, File fileOut) { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream(fileIn); out = new FileOutputStream(fileOut); PageNumber pageNumber = context.pageNumber(); int startPage = pageNumber.lookupFrontMatterLastPage(); ColumnText ct = generateTableOfContent(context); pageNumber.continueFrontMatter(); PdfReader reader = new PdfReader(in); Rectangle pageSize = reader.getPageSize(1); PdfStamper stamper = new PdfStamper(reader, out); while (true) { stamper.insertPage(++startPage, pageSize); PdfContentByte under = stamper.getUnderContent(startPage); pageNumber.notifyPageChange(); headerFooter.drawFooter(under, pageNumber.pageInfos()); PdfContentByte canvas = stamper.getOverContent(startPage); ct.setCanvas(canvas); ct.setSimpleColumn(36, 36, 559, 770); if (!ColumnText.hasMoreText(ct.go())) break; } stamper.close(); } catch (FileNotFoundException e) { log.error("Unable to reopen temporary generated file ({})", fileIn, e); } catch (DocumentException e) { log.error("Error during report post-processing from: {}, to: {}", fileIn, fileOut, e); } catch (IOException e) { log.error("Error during report post-processing from: {}, to: {}", fileIn, fileOut, e); } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(in); } }
/** * Parses a string with structured content. * * @param reader the PdfReader that has access to the PDF file * @param os the OutputStream to which the resulting xml will be written * @param charset the charset to encode the data * @since 5.0.5 */ public void convertToXml(PdfReader reader, OutputStream os, String charset) throws IOException { this.reader = reader; OutputStreamWriter outs = new OutputStreamWriter(os, charset); out = new PrintWriter(outs); // get the StructTreeRoot from the root object PdfDictionary catalog = reader.getCatalog(); PdfDictionary struct = catalog.getAsDict(PdfName.STRUCTTREEROOT); // Inspect the child or children of the StructTreeRoot inspectChild(struct.getDirectObject(PdfName.K)); out.flush(); out.close(); }
/** * Creates a VerificationData object for a PdfReader * * @param reader a reader for the document we want to verify. * @throws GeneralSecurityException */ public LtvVerifier(PdfReader reader) throws GeneralSecurityException { super(null); this.reader = reader; this.fields = reader.getAcroFields(); List<String> names = fields.getSignatureNames(); signatureName = names.get(names.size() - 1); this.signDate = new Date(); pkcs7 = coversWholeDocument(); LOGGER.info( String.format( "Checking %ssignature %s", pkcs7.isTsp() ? "document-level timestamp " : "", signatureName)); }
/** * Gets a list of X509CRL objects from a Document Security Store. * * @return a list of CRLs * @throws GeneralSecurityException * @throws IOException */ public List<X509CRL> getCRLsFromDSS() throws GeneralSecurityException, IOException { List<X509CRL> crls = new ArrayList<X509CRL>(); if (dss == null) return crls; PdfArray crlarray = dss.getAsArray(PdfName.CRLS); if (crlarray == null) return crls; CertificateFactory cf = CertificateFactory.getInstance("X.509"); for (int i = 0; i < crlarray.size(); i++) { PRStream stream = (PRStream) crlarray.getAsStream(i); X509CRL crl = (X509CRL) cf.generateCRL(new ByteArrayInputStream(PdfReader.getStreamBytes(stream))); crls.add(crl); } return crls; }
public static void main(String[] args) { try { // Read file using PdfReader PdfReader pdfReader = new PdfReader("HelloWorld.pdf"); // Modify file using PdfReader PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream("HelloWorld-modified.pdf")); Image image = Image.getInstance("temp.png"); image.scaleAbsolute(100, 50); image.setAbsolutePosition(100f, 700f); for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) { PdfContentByte content = pdfStamper.getUnderContent(i); content.addImage(image); } pdfStamper.close(); } catch (IOException | DocumentException e) { logger.warn("failed to ...." + e); } }
/** * Gets OCSP responses from the Document Security Store. * * @return a list of BasicOCSPResp objects * @throws IOException * @throws GeneralSecurityException */ public List<BasicOCSPResp> getOCSPResponsesFromDSS() throws IOException, GeneralSecurityException { List<BasicOCSPResp> ocsps = new ArrayList<BasicOCSPResp>(); if (dss == null) return ocsps; PdfArray ocsparray = dss.getAsArray(PdfName.OCSPS); if (ocsparray == null) return ocsps; for (int i = 0; i < ocsparray.size(); i++) { PRStream stream = (PRStream) ocsparray.getAsStream(i); OCSPResp ocspResponse = new OCSPResp(PdfReader.getStreamBytes(stream)); if (ocspResponse.getStatus() == 0) try { ocsps.add((BasicOCSPResp) ocspResponse.getResponseObject()); } catch (OCSPException e) { throw new GeneralSecurityException(e); } } return ocsps; }