public List<byte[]> split(byte[] input) throws IOException, DocumentException { PdfReader pdfReader = new PdfReader(input); List<byte[]> pdfFiles = new ArrayList<>(); int pageCount = pdfReader.getNumberOfPages(); int pageIndex = 0; while (++pageIndex <= pageCount) { Document document = new Document(pdfReader.getPageSizeWithRotation(pageIndex)); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); PdfCopy pdfCopy = new PdfSmartCopy(document, byteArrayOutputStream); pdfCopy.setFullCompression(); PdfImportedPage pdfImportedPage = pdfCopy.getImportedPage(pdfReader, pageIndex); document.open(); pdfCopy.addPage(pdfImportedPage); document.close(); pdfCopy.close(); pdfFiles.add(byteArrayOutputStream.toByteArray()); } return pdfFiles; }
public ImageInstance getImageByFile( PdfContentByte cb , File file ) throws IOException, BadElementException{ Image image = null; ImageInstance instance = null; if( file.getName().toLowerCase().endsWith( ".pdf")){ PdfReader reader = new PdfReader( file.getAbsolutePath() ); PdfImportedPage p = cb.getPdfWriter().getImportedPage(reader, 1); image = Image.getInstance(p); instance = new ImageInstance(image, reader); }else{ image = Image.getInstance( file.getAbsolutePath() ); instance = new ImageInstance(image, null); } instances.add(instance); return instance; }
void split(PdfReader reader, int page) throws IOException { PdfImportedPage importedPage = writer.getImportedPage(reader, page); Rectangle pageSizeToImport = reader.getPageSize(page); Iterable<Rectangle> rectangles = determineSplitRectangles(reader, page); for (Rectangle rectangle : rectangles) { newPage(rectangle); PdfContentByte directContent = writer.getDirectContent(); directContent.saveState(); directContent.rectangle(rectangle.getLeft(), rectangle.getBottom(), rectangle.getWidth(), rectangle.getHeight()); directContent.clip(); directContent.newPath(); writer.getDirectContent().addTemplate(importedPage, -pageSizeToImport.getLeft(), -pageSizeToImport.getBottom()); directContent.restoreState(); } }
void merge(PdfReader reader, PdfReaderContentParser parser, int page) throws IOException { TextMarginFinder finder = parser.processContent(page, new TextMarginFinder()); Rectangle pageSizeToImport = reader.getPageSize(page); float heightToImport = finder.getHeight(); float maxHeight = pageSize.getHeight() - topMargin - bottomMargin; if (heightToImport > maxHeight) { throw new IllegalArgumentException(String.format("Page %s content too large; height: %s, limit: %s.", page, heightToImport, maxHeight)); } if (heightToImport > yPosition - pageSize.getBottom(bottomMargin)) { newPage(); } else if (!writer.isPageEmpty()) { heightToImport += gap; } yPosition -= heightToImport; PdfImportedPage importedPage = writer.getImportedPage(reader, page); writer.getDirectContent().addTemplate(importedPage, 0, yPosition - (finder.getLly() - pageSizeToImport.getBottom())); }
/** * <a href="http://stackoverflow.com/questions/35374110/how-do-i-use-itext-to-have-a-landscaped-pdf-on-half-of-a-a4-back-to-portrait-and"> * How do i use iText to have a landscaped PDF on half of a A4 back to portrait and full size on A4 * </a> * <p> * This sample shows how to rotate and enlarge the upper half of an A4 page to fit into a new A4 page. * </p> */ @Test public void testRotateAndZoomUpperHalfPage() throws IOException, DocumentException { try ( InputStream resource = getClass().getResourceAsStream("/mkl/testarea/itext5/extract/test.pdf"); OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "test-upperHalf.pdf")) ) { PdfReader reader = new PdfReader(resource); Document document = new Document(PageSize.A4); PdfWriter writer = PdfWriter.getInstance(document, result); document.open(); double sqrt2 = Math.sqrt(2); Rectangle pageSize = reader.getPageSize(1); PdfImportedPage importedPage = writer.getImportedPage(reader, 1); writer.getDirectContent().addTemplate(importedPage, 0, sqrt2, -sqrt2, 0, pageSize.getTop() * sqrt2, -pageSize.getLeft() * sqrt2); document.close(); } }
static byte[] createMultiUseIndirectTextPdf() throws DocumentException, IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, baos); document.open(); PdfReader reader = new PdfReader(createSimpleTextPdf()); PdfImportedPage template = writer.getImportedPage(reader, 1); Rectangle pageSize = reader.getPageSize(1); writer.getDirectContent().addTemplate(template, 0, .7f, -.7f, 0, pageSize.getRight(), (pageSize.getTop() + pageSize.getBottom()) / 2); writer.getDirectContent().addTemplate(template, 0, .7f, -.7f, 0, pageSize.getRight(), pageSize.getBottom()); document.newPage(); writer.getDirectContent().addTemplate(template, pageSize.getLeft(), pageSize.getBottom()); document.close(); return baos.toByteArray(); }
static byte[] createRotatedIndirectTextPdf() throws DocumentException, IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, baos); document.open(); PdfReader reader = new PdfReader(createSimpleTextPdf()); PdfImportedPage template = writer.getImportedPage(reader, 1); Rectangle pageSize = reader.getPageSize(1); writer.getDirectContent().addTemplate(template, .7f, .7f, -.7f, .7f, 400, -200); document.newPage(); writer.getDirectContent().addTemplate(template, pageSize.getLeft(), pageSize.getBottom()); document.close(); return baos.toByteArray(); }
private static File copyToMultiplePages(CropJob cropJob) throws IOException, DocumentException { PdfReader reader = new PdfReader(cropJob.getSource().getAbsolutePath()); Document document = new Document(); File resultFile = File.createTempFile("cropped", ".pdf"); PdfSmartCopy pdfCopy = new PdfSmartCopy(document, new FileOutputStream(resultFile)); document.open(); PdfImportedPage page; for (int pageNumber = 1; pageNumber <= cropJob.getSourcePageCount(); pageNumber++) { SingleCluster currentCluster = cropJob.getClusterCollection().getSingleCluster(pageNumber); page = pdfCopy.getImportedPage(reader, pageNumber); pdfCopy.addPage(page); for (int j = 1; j < currentCluster.getRatiosList().size(); j++) { pdfCopy.addPage(page); } } document.close(); pdfCopy.close(); reader.close(); return resultFile; }
public void createPdf(String filename) throws DocumentException, IOException { Document document = new Document(PageSize.LETTER); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename)); document.open(); PdfPTable table = new PdfPTable(2); PdfReader reader = new PdfReader(T08_Chapter.RESULT); int n = reader.getNumberOfPages(); for (int pageNumber = 1; pageNumber <= n; pageNumber++) { // TODO: import page as image PdfImportedPage page = writer.getImportedPage(reader, pageNumber); table.addCell(Image.getInstance(page)); } document.add(table); document.close(); }
public void add(byte[] pdfByteArray) { try { PdfReader reader = new PdfReader(pdfByteArray); int numberOfPages = reader.getNumberOfPages(); if (this.document == null) { this.document = new Document(reader.getPageSizeWithRotation(1)); this.writer = new PdfCopy(this.document, this.getOutputStream()); this.document.open(); } PdfImportedPage page; for (int i = 0; i < numberOfPages;) { ++i; page = this.writer.getImportedPage(reader, i); this.writer.addPage(page); } PRAcroForm acroForm = reader.getAcroForm(); if (acroForm != null) { this.writer.copyAcroForm(reader); } } catch (Exception e) { e.printStackTrace(); } }
void split(PdfReader reader, int page) throws IOException { PdfImportedPage importedPage = writer.getImportedPage(reader, page); PdfContentByte directContent = writer.getDirectContent(); yPosition = pageSize.getTop(); Rectangle pageSizeToImport = reader.getPageSize(page); float[] borderPositions = determineSplitPositions(reader, page); if (borderPositions == null || borderPositions.length < 2) return; for (int borderIndex = 0; borderIndex + 1 < borderPositions.length; borderIndex++) { float height = borderPositions[borderIndex] - borderPositions[borderIndex + 1]; if (height <= 0) continue; directContent.saveState(); directContent.rectangle(0, yPosition - height, pageSizeToImport.getWidth(), height); directContent.clip(); directContent.newPath(); writer.getDirectContent().addTemplate(importedPage, 0, yPosition - (borderPositions[borderIndex] - pageSizeToImport.getBottom())); directContent.restoreState(); newPage(); } }
@Test public void testWithWriter() throws DocumentException, IOException { InputStream resourceStream = getClass().getResourceAsStream("test.pdf"); try { PdfReader reader = new PdfReader(resourceStream); Rectangle pageSize = reader.getPageSize(1); Rectangle rect = getOutputPageSize(pageSize, reader, 1); Document document = new Document(rect, 0, 0, 0, 0); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "test-trimmed-writer.pdf"))); document.open(); PdfImportedPage page; // Go through all pages int n = reader.getNumberOfPages(); for (int i = 1; i <= n; i++) { document.newPage(); page = writer.getImportedPage(reader, i); System.out.println("BBox: "+ page.getBoundingBox().toString()); Image instance = Image.getInstance(page); document.add(instance); Rectangle outputPageSize = document.getPageSize(); System.out.println(outputPageSize.toString()); } document.close(); } finally { if (resourceStream != null) resourceStream.close(); } }
/** * This methods creates a copy of the source document containing each page twice, * once with the cropbox limited to the left half page, once to the right one. */ void splitIntoHalfPages(InputStream source, File target) throws IOException, DocumentException { final PdfReader reader = new PdfReader(source); try ( OutputStream targetStream = new FileOutputStream(target) ) { Document document = new Document(); PdfCopy copy = new PdfCopy(document, targetStream); document.open(); for (int page = 1; page <= reader.getNumberOfPages(); page++) { PdfDictionary pageN = reader.getPageN(page); Rectangle cropBox = reader.getCropBox(page); PdfArray leftBox = new PdfArray(new float[]{cropBox.getLeft(), cropBox.getBottom(), (cropBox.getLeft() + cropBox.getRight()) / 2.0f, cropBox.getTop()}); PdfArray rightBox = new PdfArray(new float[]{(cropBox.getLeft() + cropBox.getRight()) / 2.0f, cropBox.getBottom(), cropBox.getRight(), cropBox.getTop()}); PdfImportedPage importedPage = copy.getImportedPage(reader, page); pageN.put(PdfName.CROPBOX, leftBox); copy.addPage(importedPage); pageN.put(PdfName.CROPBOX, rightBox); copy.addPage(importedPage); } document.close(); } finally { reader.close(); } }
public static byte[] Merge(File[] documentPaths) throws IOException, DocumentException { byte[] mergedDocument; try (ByteArrayOutputStream memoryStream = new ByteArrayOutputStream()) { Document document = new Document(); PdfSmartCopy pdfSmartCopy = new PdfSmartCopy(document, memoryStream); document.open(); for (File docPath : documentPaths) { PdfReader reader = new PdfReader(docPath.toString()); try { reader.consolidateNamedDestinations(); int numberOfPages = reader.getNumberOfPages(); for (int page = 0; page < numberOfPages;) { PdfImportedPage pdfImportedPage = pdfSmartCopy.getImportedPage(reader, ++page); pdfSmartCopy.addPage(pdfImportedPage); } } finally { reader.close(); } } document.close(); mergedDocument = memoryStream.toByteArray(); } return mergedDocument; }
public static byte[] ExtractPages(String pdfDocument, int startPage, int endPage) throws IOException, DocumentException { try (InputStream pdfDocumentStream = SmartMerging.class.getResourceAsStream(pdfDocument)) { PdfReader reader = new PdfReader(pdfDocumentStream); int numberOfPages = reader.getNumberOfPages(); int endPageResolved = endPage > 0 ? endPage : numberOfPages; if (startPage > numberOfPages || endPageResolved > numberOfPages) System.err.printf("Error: page indices (%s, %s) out of bounds. Document has {2} pages.", startPage, endPageResolved, numberOfPages); byte[] outputDocument; try (ByteArrayOutputStream msOut = new ByteArrayOutputStream()) { Document doc = new Document(); PdfCopy pdfCopyProvider = new PdfCopy(doc, msOut); doc.open(); for (int i = startPage; i <= endPageResolved; i++) { PdfImportedPage page = pdfCopyProvider.getImportedPage(reader, i); pdfCopyProvider.addPage(page); } doc.close(); reader.close(); outputDocument = msOut.toByteArray(); } return outputDocument; } }
public void addPage(PdfReader reader, int pageNumber, PdfRectangle cropBox) throws TaskException { PdfImportedPage page = pdfCopy.getImportedPage(reader, pageNumber); PdfDictionary dictionary = reader.getPageN(pageNumber); dictionary.put(PdfName.MEDIABOX, cropBox); dictionary.put(PdfName.CROPBOX, cropBox); addPage(page); }
public void createPdf(String filename) throws DocumentException, IOException { Document document = new Document(PageSize.LETTER); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename)); // TODO: 3. get imported page PdfReader stationery = new PdfReader(T11_ColumnText.RESULT); PdfImportedPage page = writer.getImportedPage(stationery, 1); writer.setPageEvent(new HeaderFooter(page)); document.open(); // step 4 - add content into document for (int i = 1; i <= 10; i++) { Chapter chapter = new Chapter(String.format("Chapter %s", i), i); Section section = chapter.addSection("Section"); section.add(new Paragraph("TestTestTestTestTestTestTestTestTestTestTestTest")); for (int j = 1; j <= 3; j++) { Section subSection = section.addSection("Sub Section"); subSection.add(new Paragraph("TestTestTestTestTestTestTestTestTestTestTestTest")); } document.add(chapter); } document.close(); }
void merge(PdfReader reader, PdfReaderContentParser parser, int page) throws IOException { PdfImportedPage importedPage = writer.getImportedPage(reader, page); PdfContentByte directContent = writer.getDirectContent(); PageVerticalAnalyzer finder = parser.processContent(page, new PageVerticalAnalyzer()); if (finder.verticalFlips.size() < 2) return; Rectangle pageSizeToImport = reader.getPageSize(page); int startFlip = finder.verticalFlips.size() - 1; boolean first = true; while (startFlip > 0) { if (!first) newPage(); float freeSpace = yPosition - pageSize.getBottom(bottomMargin); int endFlip = startFlip + 1; while ((endFlip > 1) && (finder.verticalFlips.get(startFlip) - finder.verticalFlips.get(endFlip - 2) < freeSpace)) endFlip -=2; if (endFlip < startFlip) { float height = finder.verticalFlips.get(startFlip) - finder.verticalFlips.get(endFlip); directContent.saveState(); directContent.rectangle(0, yPosition - height, pageSizeToImport.getWidth(), height); directContent.clip(); directContent.newPath(); writer.getDirectContent().addTemplate(importedPage, 0, yPosition - (finder.verticalFlips.get(startFlip) - pageSizeToImport.getBottom())); directContent.restoreState(); yPosition -= height + gap; startFlip = endFlip - 1; } else if (!first) throw new IllegalArgumentException(String.format("Page %s content sections too large.", page)); first = false; } }
/** * <a href="http://stackoverflow.com/questions/28911509/how-to-retain-page-labels-when-concatenating-an-existing-pdf-with-a-pdf-created"> * How to retain page labels when concatenating an existing pdf with a pdf created from scratch? * </a> * <p> * A proposal how to implement the task using a {@link PdfStamper}. */ @Test public void testInsertTitlePage() throws IOException, DocumentException { try ( InputStream documentStream = getClass().getResourceAsStream("Labels.pdf"); InputStream titleStream = getClass().getResourceAsStream("Cover.pdf"); OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "labels-with-cover-page.pdf")) ) { PdfReader titleReader = new PdfReader(titleStream); PdfReader reader = new PdfReader(documentStream); PdfStamper stamper = new PdfStamper(reader, outputStream); PdfImportedPage page = stamper.getImportedPage(titleReader, 1); stamper.insertPage(1, titleReader.getPageSize(1)); PdfContentByte content = stamper.getUnderContent(1); content.addTemplate(page, 0, 0); copyLinks(stamper, 1, titleReader, 1); PdfDictionary root = reader.getCatalog(); PdfDictionary labels = root.getAsDict(PdfName.PAGELABELS); if (labels != null) { PdfArray newNums = new PdfArray(); newNums.add(new PdfNumber(0)); PdfDictionary coverDict = new PdfDictionary(); coverDict.put(PdfName.P, new PdfString("Cover Page")); newNums.add(coverDict); PdfArray nums = labels.getAsArray(PdfName.NUMS); if (nums != null) { for (int i = 0; i < nums.size() - 1; ) { int n = nums.getAsNumber(i++).intValue(); newNums.add(new PdfNumber(n+1)); newNums.add(nums.getPdfObject(i++)); } } labels.put(PdfName.NUMS, newNums); stamper.markUsed(labels); } stamper.close(); } }
/** * <a href="http://stackoverflow.com/questions/29977927/table-header-in-pdf-getting-displayed-using-itextpdf5-1-1-but-not-in-itextpdf5-5"> * table header in pdf getting displayed using itextpdf5.1.1 but not in itextpdf5.5.3 * </a> * <p> * Indeed, the code as presented by the OP does not show the header table. This makes sense, though: * </p> * <p> * The OP has cells with default padding (i.e. 2) and height 10, and he tries to insert text at height 7. * But 2 (top margin) + 7 (text height) + 2 (bottom margin) = 11, i.e. more than fits into the cell height 10. * Thus, the text does not fit and is not displayed. * </p> * <p> * You can fix this by either * <ul> * <li>using a smaller font, e.g. 6, or * <li>using a higher cell, e.g. 11, or * <li>using a smaller padding, e.g. 1, see below- * </p> */ @Test public void testSandeepSinghHeaderTable() throws DocumentException, IOException { byte[] strIntermediatePDFFile = createSampleDocument(); String header1 = "Header 1"; String header2 = "Header 2"; String header3 = "Header 3"; String header5 = "Header 5"; Document document = new Document(PageSize.A4.rotate(), 20, 20, 75, 20); PdfCopy copy = new PdfCopy(document, new FileOutputStream(new File(RESULT_FOLDER, "stampTableHeader.pdf"))); document.open(); PdfReader pdfReaderIntermediate = new PdfReader(strIntermediatePDFFile); int numberOfPages = pdfReaderIntermediate.getNumberOfPages(); Font ffont = new Font(Font.FontFamily.UNDEFINED, 7, Font.NORMAL); System.out.println("###### No. of Pages: " + numberOfPages); for (int j = 0; j < numberOfPages; ) { PdfImportedPage page = copy.getImportedPage(pdfReaderIntermediate, ++j); PageStamp stamp = copy.createPageStamp(page); Phrase footer = new Phrase(String.format("%d of %d", j, numberOfPages), ffont); ColumnText.showTextAligned(stamp.getUnderContent(), Element.ALIGN_CENTER, footer, (document.right() - document.left()) / 2 + document.leftMargin(), document.bottom() - 10, 0); if (j != 1) { PdfPTable headerTable = new PdfPTable(2); headerTable.setTotalWidth(700); headerTable.getDefaultCell().setFixedHeight(10); headerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER); headerTable.getDefaultCell().setPadding(1); // Added! headerTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT); headerTable.addCell(new Phrase(String.format(header1), ffont)); headerTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT); headerTable.addCell(new Phrase(String.format(header2), ffont)); headerTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT); headerTable.addCell(new Phrase(String.format(header3), ffont)); headerTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT); headerTable.addCell(new Phrase(String.format(header5, j), ffont)); headerTable.completeRow(); headerTable.writeSelectedRows(0, 5, 60.5f, 550, stamp.getUnderContent()); } stamp.alterContents(); copy.addPage(page); } document.close(); }
private static File copyToMultiplePages(final CropDefinition cropDefinition, final PdfMetaInformation pdfMetaInformation) throws IOException, DocumentException { PdfReader reader = new PdfReader(cropDefinition.getSourceFile().getAbsolutePath()); HashMap<String, String> map = SimpleNamedDestination.getNamedDestination(reader, false); Document document = new Document(); File resultFile = File.createTempFile("cropped", ".pdf"); PdfSmartCopy pdfCopy = new PdfSmartCopy(document, new FileOutputStream(resultFile)); document.open(); Map<Integer, List<String>> pageNrToDestinations = new HashMap<Integer, List<String>>(); for (String single : map.keySet()) { StringTokenizer st = new StringTokenizer(map.get(single), " "); if (st.hasMoreElements()) { String pageNrString = (String) st.nextElement(); int pageNr = Integer.parseInt(pageNrString); List<String> singleList = (pageNrToDestinations.get(pageNr)); if (singleList == null) { singleList = new ArrayList<String>(); singleList.add(single); pageNrToDestinations.put(pageNr, singleList); } else { singleList.add(single); } } } int outputPageNumber = 0; for (int pageNumber = 1; pageNumber <= pdfMetaInformation.getSourcePageCount(); pageNumber++) { PdfImportedPage pdfPage = pdfCopy.getImportedPage(reader, pageNumber); pdfCopy.addPage(pdfPage); outputPageNumber++; List<String> destinations = pageNrToDestinations.get(pageNumber); if (destinations != null) { for (String destination : destinations) pdfCopy.addNamedDestination(destination, outputPageNumber, new PdfDestination(PdfDestination.FIT)); } List<Float[]> rectangles = cropDefinition.getRectanglesForPage(pageNumber); for (int j = 1; j < rectangles.size(); j++) { pdfCopy.addPage(pdfPage); outputPageNumber++; } } document.close(); pdfCopy.close(); reader.close(); return resultFile; }
/** * Manipulates a PDF file src with the file dest as result * @param src the original PDF * @param dest the resulting PDF * @param pow the PDF will be N-upped with N = Math.pow(2, pow); * @throws IOException * @throws DocumentException * @throws SQLException */ public static void manipulatePdf(String src, String dest, int pow) throws IOException, DocumentException { PdfReader reader = new PdfReader(src); Rectangle badgeSize = reader.getPageSize(1); Document document = new Document(PageSize.A4.rotate(), 0, 0, 0, 0); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest)); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfImportedPage page; float offsetX, offsetY, factor; float borderX = 0.1f * badgeSize.getWidth(); float borderY = 0.1f * badgeSize.getHeight(); int badgeOffset = 0; int maxBadgesPerPage = 5; int total = reader.getNumberOfPages(); for (int i = 0; i < total; ) { if (i % maxBadgesPerPage == 0) { // break after 5 Badges document.newPage(); badgeOffset = 0; } factor = 1; // add badge front offsetX = badgeOffset * badgeSize.getWidth() + borderX; offsetY = document.getPageSize().getHeight() - 1 * badgeSize.getHeight() -borderY; page = writer.getImportedPage(reader, i+1); cb.addTemplate(page, factor, 0, 0, factor, offsetX, offsetY); // add badge back offsetX = offsetX + badgeSize.getWidth(); // offsetY = document.getPageSize().getHeight() - 2 * badgeSize.getHeight() -borderY; page = writer.getImportedPage(reader, i+2); cb.addTemplate(page, -factor, 0, 0, -factor, offsetX, offsetY); badgeOffset++; i = i+2; } document.close(); reader.close(); }
public HeaderFooter(PdfImportedPage page) { this.page = page; }