Java Code Examples for com.itextpdf.text.pdf.PdfReader#getPageN()

The following examples show how to use com.itextpdf.text.pdf.PdfReader#getPageN() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HideContent.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/43870545/filling-a-pdf-with-itextsharp-and-then-hiding-the-base-layer">
 * Filling a PDF with iTextsharp and then hiding the base layer
 * </a>
 * <p>
 * This test shows how to remove all content.
 * </p>
 */
@Test
public void testRemoveContent() throws IOException, DocumentException
{
    try (   InputStream resource = getClass().getResourceAsStream("document.pdf");
            OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "document-removedContent.pdf")))
    {
        PdfReader pdfReader = new PdfReader(resource);
        for (int page = 1; page <= pdfReader.getNumberOfPages(); page++)
        {
            PdfDictionary pageDictionary = pdfReader.getPageN(page);
            pageDictionary.remove(PdfName.CONTENTS);
        }
        new PdfStamper(pdfReader, result).close();
    }
}
 
Example 2
Source File: SwitchPageCanvas.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/34394199/i-cant-rotate-my-page-from-existing-pdf">
 * I can't rotate my page from existing PDF
 * </a>
 * <p>
 * Switching between portrait and landscape like this obviously will cut off some parts of the page.
 * </p>
 */
@Test
public void testSwitchOrientation() throws DocumentException, IOException
{
    try (InputStream resourceStream = getClass().getResourceAsStream("/mkl/testarea/itext5/extract/n2013.00849449.pdf"))
    {
        PdfReader reader = new PdfReader(resourceStream);
        int n = reader.getNumberOfPages();
        PdfDictionary pageDict;
        for (int i = 1; i <= n; i++) {
            Rectangle rect = reader.getPageSize(i);
            Rectangle crop = reader.getCropBox(i);
            pageDict = reader.getPageN(i);
            pageDict.put(PdfName.MEDIABOX, new PdfArray(new float[] {rect.getBottom(), rect.getLeft(), rect.getTop(), rect.getRight()}));
            pageDict.put(PdfName.CROPBOX, new PdfArray(new float[] {crop.getBottom(), crop.getLeft(), crop.getTop(), crop.getRight()}));
        }
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(new File(RESULT_FOLDER, "n2013.00849449-switch.pdf")));
        stamper.close();
        reader.close();
    }
}
 
Example 3
Source File: PdfContentStreamEditor.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * This method edits the immediate contents of a page, i.e. its content stream.
 * It explicitly does not descent into form xobjects, patterns, or annotations.
 */
public void editPage(PdfStamper pdfStamper, int pageNum) throws IOException {
    PdfReader pdfReader = pdfStamper.getReader();
    PdfDictionary page = pdfReader.getPageN(pageNum);
    byte[] pageContentInput = ContentByteUtils.getContentBytesForPage(pdfReader, pageNum);
    page.remove(PdfName.CONTENTS);
    editContent(pageContentInput, page.getAsDict(PdfName.RESOURCES), pdfStamper.getUnderContent(pageNum));
}
 
Example 4
Source File: MarkAnnotationReadOnly.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/37275267/how-to-make-pdf-annotation-as-read-only-using-itext">
 * how to make pdf annotation as read only using itext?
 * </a>
 * <br/>
 * test-annotated.pdf <i>simple PDF with sticky note</i>
 * 
 * <p>
 * This test shows how to set the read-only flags of all annotations of a document.
 * </p>
 */
@Test
public void testMarkAnnotationsReadOnly() throws IOException, DocumentException
{
    try (   InputStream resourceStream = getClass().getResourceAsStream("test-annotated.pdf");
            OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "test-annotated-ro.pdf"))    )
    {
        PdfReader reader = new PdfReader(resourceStream);
        PdfStamper stamper = new PdfStamper(reader, outputStream);

        for (int page = 1; page <= reader.getNumberOfPages(); page++)
        {
            PdfDictionary pageDictionary = reader.getPageN(page);
            PdfArray annotationArray = pageDictionary.getAsArray(PdfName.ANNOTS);
            if (annotationArray == null)
                continue;
            for (PdfObject object : annotationArray)
            {
                PdfObject directObject = PdfReader.getPdfObject(object);
                if (directObject instanceof PdfDictionary)
                {
                    PdfDictionary annotationDictionary = (PdfDictionary) directObject;
                    PdfNumber flagsNumber = annotationDictionary.getAsNumber(PdfName.F);
                    int flags = flagsNumber != null ? flagsNumber.intValue() : 0;
                    flags |= PdfAnnotation.FLAGS_READONLY;
                    annotationDictionary.put(PdfName.F, new PdfNumber(flags));
                }
            }
        }

        stamper.close();
    }
}
 
Example 5
Source File: TestTrimPdfPage.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testWithStamper() throws DocumentException, IOException
{
    InputStream resourceStream = getClass().getResourceAsStream("test.pdf");
    try
    {
        PdfReader reader = new PdfReader(resourceStream);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(new File(RESULT_FOLDER, "test-trimmed-stamper.pdf")));
        
        // Go through all pages
        int n = reader.getNumberOfPages();
        for (int i = 1; i <= n; i++)
        {
            Rectangle pageSize = reader.getPageSize(i);
            Rectangle rect = getOutputPageSize(pageSize, reader, i);

            PdfDictionary page = reader.getPageN(i);
            page.put(PdfName.CROPBOX, new PdfArray(new float[]{rect.getLeft(), rect.getBottom(), rect.getRight(), rect.getTop()}));
            stamper.markUsed(page);
        }
        stamper.close();
    }
    finally
    {
        if (resourceStream != null)
            resourceStream.close();
    }
}
 
Example 6
Source File: TestTrimPdfPage.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testWithStamperTopBottom() throws DocumentException, IOException
{
    InputStream resourceStream = getClass().getResourceAsStream("test.pdf");
    try
    {
        PdfReader reader = new PdfReader(resourceStream);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(new File(RESULT_FOLDER, "test-trimmed-stamper-top-bottom.pdf")));
        
        // Go through all pages
        int n = reader.getNumberOfPages();
        for (int i = 1; i <= n; i++)
        {
            Rectangle pageSize = reader.getPageSize(i);
            Rectangle rect = getOutputPageSize2(pageSize, reader, i);

            PdfDictionary page = reader.getPageN(i);
            page.put(PdfName.CROPBOX, new PdfArray(new float[]{rect.getLeft(), rect.getBottom(), rect.getRight(), rect.getTop()}));
            stamper.markUsed(page);
        }
        stamper.close();
    }
    finally
    {
        if (resourceStream != null)
            resourceStream.close();
    }
}
 
Example 7
Source File: TestTrimPdfPage.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testWithStamperCentered() throws DocumentException, IOException
{
    InputStream resourceStream = getClass().getResourceAsStream("test.pdf");
    try
    {
        PdfReader reader = new PdfReader(resourceStream);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(new File(RESULT_FOLDER, "test-trimmed-stamper-centered.pdf")));
        
        // Go through all pages
        int n = reader.getNumberOfPages();
        for (int i = 1; i <= n; i++)
        {
            Rectangle pageSize = reader.getPageSize(i);
            Rectangle rect = getOutputPageSize3(pageSize, reader, i);

            PdfDictionary page = reader.getPageN(i);
            page.put(PdfName.CROPBOX, new PdfArray(new float[]{rect.getLeft(), rect.getBottom(), rect.getRight(), rect.getTop()}));
            stamper.markUsed(page);
        }
        stamper.close();
    }
    finally
    {
        if (resourceStream != null)
            resourceStream.close();
    }
}
 
Example 8
Source File: TestTrimPdfPage.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testWithStamperExtFinder() throws DocumentException, IOException
{
    InputStream resourceStream = getClass().getResourceAsStream("test.pdf");
    try
    {
        PdfReader reader = new PdfReader(resourceStream);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(new File(RESULT_FOLDER, "test-trimmed-stamper-ext.pdf")));
        
        // Go through all pages
        int n = reader.getNumberOfPages();
        for (int i = 1; i <= n; i++)
        {
            Rectangle pageSize = reader.getPageSize(i);
            Rectangle rect = getOutputPageSize4(pageSize, reader, i);

            PdfDictionary page = reader.getPageN(i);
            page.put(PdfName.CROPBOX, new PdfArray(new float[]{rect.getLeft(), rect.getBottom(), rect.getRight(), rect.getTop()}));
            stamper.markUsed(page);
        }
        stamper.close();
    }
    finally
    {
        if (resourceStream != null)
            resourceStream.close();
    }
}
 
Example 9
Source File: SplitIntoHalfPages.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 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();
    }
}
 
Example 10
Source File: ShrinkRotated.java    From testarea-itext5 with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/48601115/pdf-shrink-causing-change-in-orientation">
 * PDF Shrink causing change in Orientation
 * </a>
 * <p>
 * Sample.PDF - retrieved via e-mail
 * </p>
 * <p>
 * This issue is just another result of iText adding rotations to the
 * transformation matrices at the start of undercontent and overcontent
 * of rotated pages: Due to the nature of the literal the OP adds to
 * the undercontent, this rotation bleeds through and also affects the
 * original content.
 * </p>
 */
@Test
public void testShrinkSample() throws IOException, DocumentException {
    float xPercentage = 0.3F;
    float yPercentage = 0.6F;
    try (   InputStream resource = getClass().getResourceAsStream("Sample.PDF");
            OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "Sample-shrunken.PDF"))) {
        PdfReader reader = new PdfReader(resource);
        PdfStamper stamper = new PdfStamper(reader, result);
        //vvv
        stamper.setRotateContents(false);
        //^^^
        for (int p = 1; p <= 1; p++) {
            float offsetX = (reader.getPageSize(p).getWidth() * (1 - xPercentage)) / 2;
            float offsetY = (reader.getPageSize(p).getHeight() * (1 - yPercentage)) / 2;
            PdfDictionary page;
            PdfArray crop;
            PdfArray media;
            page = reader.getPageN(p);
            System.out.println("reader.getPateRoatation-->"+reader.getPageRotation(p));
            media = page.getAsArray(PdfName.CROPBOX);
            if (media == null) {
                media = page.getAsArray(PdfName.MEDIABOX);
            }
            crop = new PdfArray();
            crop.add(new PdfNumber(0));
            crop.add(new PdfNumber(0));
            crop.add(new PdfNumber(media.getAsNumber(2).floatValue()));
            crop.add(new PdfNumber(media.getAsNumber(3).floatValue()));
            page.put(PdfName.MEDIABOX, crop);
            page.put(PdfName.CROPBOX, crop);
            Rectangle mediabox = reader.getPageSize(p);
            stamper.getUnderContent(p).setLiteral(
                    String.format("\nq %s %s %s %s %s %s cm\nq\n",
                    xPercentage, mediabox.getLeft(),mediabox.getBottom(), yPercentage,  offsetX, offsetY));
            stamper.getOverContent(p).setLiteral("\nQ\nQ\n");           
        }
        stamper.close();
        reader.close();
    }
}
 
Example 11
Source File: SearchActionJavaScript.java    From testarea-itext5 with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/41090131/searching-pdf-for-a-specific-string-in-javascript-action-in-itext">
 * Searching PDF for a specific string in JavaScript action in iText
 * </a>
 * <br/>
 * <a href="http://www21.zippyshare.com/v/RDdOJI97/file.html">
 * file.pdf
 * </a>
 * <p>
 * This test shows how to process the immediate JavaScript code in annotation actions.
 * </p> 
 */
@Test
public void testSearchJsActionInFile() throws IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("file.pdf")   )
    {
        System.out.println("file.pdf - Looking for special JavaScript actions.");
        // Reads and parses a PDF document
        PdfReader reader = new PdfReader(resource);

        // For each PDF page
        for (int i = 1; i <= reader.getNumberOfPages(); i++)
        {
            System.out.printf("\nPage %d\n", i);
            // Get a page a PDF page
            PdfDictionary page = reader.getPageN(i);
            // Get all the annotations of page i
            PdfArray annotsArray = page.getAsArray(PdfName.ANNOTS);

            // If page does not have annotations
            if (annotsArray == null)
            {
                System.out.printf("No annotations.\n", i);
                continue;
            }

            // For each annotation
            for (int j = 0; j < annotsArray.size(); ++j)
            {
                System.out.printf("Annotation %d - ", j);

                // For current annotation
                PdfDictionary curAnnot = annotsArray.getAsDict(j);

                // check if has JS as described below
                PdfDictionary annotationAction = curAnnot.getAsDict(PdfName.A);
                if (annotationAction == null)
                {
                    System.out.print("no action");
                }
                // test if it is a JavaScript action
                else if (PdfName.JAVASCRIPT.equals(annotationAction.get(PdfName.S)))
                {
                    PdfObject scriptObject = annotationAction.getDirectObject(PdfName.JS);
                    if (scriptObject == null)
                    {
                        System.out.print("missing JS entry");
                        continue;
                    }
                    final String script;
                    if (scriptObject.isString())
                        script = ((PdfString)scriptObject).toUnicodeString();
                    else if (scriptObject.isStream())
                    {
                        try (   ByteArrayOutputStream baos = new ByteArrayOutputStream()    )
                        {
                            ((PdfStream)scriptObject).writeContent(baos);
                            script = baos.toString("ISO-8859-1");
                        }
                    }
                    else
                    {
                        System.out.println("malformed JS entry");
                        continue;
                    }

                    if (script.contains("if (this.hostContainer) { try {"))
                        System.out.print("contains test string - ");

                    System.out.printf("\n---\n%s\n---", script);
                    // what here?
                }
                else
                {
                    System.out.print("no JavaScript action");
                }
                System.out.println();
            }
        }
    }
}
 
Example 12
Source File: ProcessLink.java    From testarea-itext5 with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/49370352/how-do-i-get-a-get-destination-page-of-a-link-in-pdf-file">
 * How do I get a get destination page of a link in PDF file?
 * </a>
 * <br/>
 * local-link.pdf - output of the test {@link CreateLink}.
 * <p>
 * This test shows how to access data of the target page, once by
 * directly reading from the page dictionary referenced from the
 * link destination, once by first determining the page number and
 * then using {@link PdfReader} helper methods.
 * </p>
 */
@Test
public void testDetermineTargetPage() throws IOException {
    try (   InputStream src = getClass().getResourceAsStream("local-link.pdf")  ) {
        PdfReader reader = new PdfReader(src);
        PdfDictionary page = reader.getPageN(1);
        PdfArray annots = page.getAsArray(PdfName.ANNOTS); 
        for (int i = 0; i < annots.size(); i++) {
            PdfDictionary annotation = annots.getAsDict(i);
            if (PdfName.LINK.equals(annotation.getAsName(PdfName.SUBTYPE))) {
                PdfArray d = annotation.getAsArray(PdfName.DEST);
                if (d == null) {
                    PdfDictionary action = annotation.getAsDict(PdfName.A);
                    if (action != null)
                        d = action.getAsArray(PdfName.D);
                }
                    
                if (d != null && d.size() > 0) {
                    System.out.println("Next destination -");
                    PdfIndirectReference pageReference = d.getAsIndirectObject(0);

                    // Work with target dictionary directly
                    PdfDictionary pageDict = d.getAsDict(0);
                    PdfArray boxArray = pageDict.getAsArray(PdfName.CROPBOX);
                    if (boxArray == null) {
                        boxArray = pageDict.getAsArray(PdfName.MEDIABOX);
                    }
                    Rectangle box = PdfReader.getNormalizedRectangle(boxArray);
                    System.out.printf("* Target page object %s has cropbox %s\n", pageReference, box);

                    // Work via page number
                    for (int pageNr = 1; pageNr <= reader.getNumberOfPages(); pageNr++) {
                        PRIndirectReference pp = reader.getPageOrigRef(pageNr);
                        if (pp.getGeneration() == pageReference.getGeneration() && pp.getNumber() == pageReference.getNumber()) {
                            System.out.printf("* Target page %s has cropbox %s\n", pageNr, reader.getCropBox(pageNr));
                            break;
                        }
                    }
                }
            }
        }
    }
}
 
Example 13
Source File: CropManager.java    From Briss-2.0 with GNU General Public License v3.0 4 votes vote down vote up
private static void cropMultipliedFile(File source, CropJob cropJob) throws DocumentException,
    IOException {

    PdfReader reader = new PdfReader(source.getAbsolutePath());
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(cropJob.getDestinationFile()));
    stamper.setMoreInfo(cropJob.getSourceMetaInfo());

    PdfDictionary pageDict;
    int newPageNumber = 1;
    for (int origPageNumber = 1; origPageNumber <= cropJob.getSourcePageCount(); origPageNumber++) {
        SingleCluster cluster = cropJob.getClusterCollection().getSingleCluster(origPageNumber);

        // if no crop was selected do nothing
        if (cluster.getRatiosList().size() == 0) {
            newPageNumber++;
            continue;
        }

        for (Float[] ratios : cluster.getRatiosList()) {

            pageDict = reader.getPageN(newPageNumber);

            List<Rectangle> boxes = new ArrayList<Rectangle>();
            boxes.add(reader.getBoxSize(newPageNumber, "media"));
            boxes.add(reader.getBoxSize(newPageNumber, "crop"));
            int rotation = reader.getPageRotation(newPageNumber);

            Rectangle scaledBox = calculateScaledRectangle(boxes, ratios, rotation);

            PdfArray scaleBoxArray = new PdfArray();
            scaleBoxArray.add(new PdfNumber(scaledBox.getLeft()));
            scaleBoxArray.add(new PdfNumber(scaledBox.getBottom()));
            scaleBoxArray.add(new PdfNumber(scaledBox.getRight()));
            scaleBoxArray.add(new PdfNumber(scaledBox.getTop()));

            pageDict.put(PdfName.CROPBOX, scaleBoxArray);
            pageDict.put(PdfName.MEDIABOX, scaleBoxArray);
            // increment the pagenumber
            newPageNumber++;
        }
        int[] range = new int[2];
        range[0] = newPageNumber - 1;
        range[1] = cropJob.getSourcePageCount() + (newPageNumber - origPageNumber);
        SimpleBookmark.shiftPageNumbers(cropJob.getSourceBookmarks(), cluster.getRatiosList().size() - 1, range);
    }
    stamper.setOutlines(cropJob.getSourceBookmarks());
    stamper.close();
    reader.close();
}
 
Example 14
Source File: DocumentCropper.java    From Briss-2.0 with GNU General Public License v3.0 4 votes vote down vote up
private static void cropMultipliedFile(final CropDefinition cropDefinition, final File multipliedDocument,
                                       final PdfMetaInformation pdfMetaInformation) throws DocumentException, IOException {

    PdfReader reader = new PdfReader(multipliedDocument.getAbsolutePath());

    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(cropDefinition.getDestinationFile()));
    stamper.setMoreInfo(pdfMetaInformation.getSourceMetaInfo());

    PdfDictionary pageDict;
    int newPageNumber = 1;

    for (int sourcePageNumber = 1; sourcePageNumber <= pdfMetaInformation.getSourcePageCount(); sourcePageNumber++) {

        List<Float[]> rectangleList = cropDefinition.getRectanglesForPage(sourcePageNumber);

        // if no crop was selected do nothing
        if (rectangleList.isEmpty()) {
            newPageNumber++;
            continue;
        }

        for (Float[] ratios : rectangleList) {

            pageDict = reader.getPageN(newPageNumber);

            List<Rectangle> boxes = new ArrayList<Rectangle>();
            boxes.add(reader.getBoxSize(newPageNumber, "media"));
            boxes.add(reader.getBoxSize(newPageNumber, "crop"));
            int rotation = reader.getPageRotation(newPageNumber);

            Rectangle scaledBox = RectangleHandler.calculateScaledRectangle(boxes, ratios, rotation);

            PdfArray scaleBoxArray = createScaledBoxArray(scaledBox);

            pageDict.put(PdfName.CROPBOX, scaleBoxArray);
            pageDict.put(PdfName.MEDIABOX, scaleBoxArray);
            // increment the pagenumber
            newPageNumber++;
        }
        int[] range = new int[2];
        range[0] = newPageNumber - 1;
        range[1] = pdfMetaInformation.getSourcePageCount() + (newPageNumber - sourcePageNumber);
        SimpleBookmark.shiftPageNumbers(pdfMetaInformation.getSourceBookmarks(), rectangleList.size() - 1, range);
    }
    stamper.setOutlines(pdfMetaInformation.getSourceBookmarks());
    stamper.close();
    reader.close();
}
 
Example 15
Source File: ImportPageWithoutFreeSpace.java    From testarea-itext5 with GNU Affero General Public License v3.0 3 votes vote down vote up
/**
 * <p>
 * This method restricts the media boxes of the pages in the given {@link PdfReader}
 * to the actual content found by the {@link MarginFinder} extended render listener.
 * </p>
 * <p>
 * It essentially is copied from the {@link TestTrimPdfPage} methods
 * {@link TestTrimPdfPage#testWithStamperExtFinder()} and
 * {@link TestTrimPdfPage#getOutputPageSize4(Rectangle, PdfReader, int)}.
 * In contrast to the code there this method manipulates
 * the media box because this is the only box respected by
 * {@link PdfWriter#getImportedPage(PdfReader, int)}.
 * </p>
 */
static void cropPdf(PdfReader reader) throws IOException
{
    int n = reader.getNumberOfPages();
    for (int i = 1; i <= n; i++)
    {
        PdfReaderContentParser parser = new PdfReaderContentParser(reader);
        MarginFinder finder = parser.processContent(i, new MarginFinder());
        Rectangle rect = new Rectangle(finder.getLlx(), finder.getLly(), finder.getUrx(), finder.getUry());

        PdfDictionary page = reader.getPageN(i);
        page.put(PdfName.MEDIABOX, new PdfArray(new float[]{rect.getLeft(), rect.getBottom(), rect.getRight(), rect.getTop()}));
    }
}
 
Example 16
Source File: ImageExtraction.java    From testarea-itext5 with GNU Affero General Public License v3.0 3 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/47101222/how-to-decode-image-with-asciihexdecode">
 * How to decode image with /ASCIIHexDecode
 * </a>
 * <br/>
 * <a href="https://1drv.ms/b/s!AjcEvFO-aWLMkbtXNVl_rmUXv6nnBQ">
 * test.pdf
 * </a>
 * <p>
 * The issue can be reproduced. Without studying the format
 * of the integrated image in detail, though, it is hard to
 * tell whether this is a bug in iText or a bug in the PDF.
 * </p>
 */
@Test
public void testExtractImageLikeSteveB() throws IOException
{
    try (InputStream resource = getClass().getResourceAsStream("testSteveB.pdf")) {
        PdfReader reader = new PdfReader(resource);
        for (int pageNumber = 1; pageNumber <= reader.getNumberOfPages(); pageNumber++)
        {
            PdfDictionary dictionary = reader.getPageN(pageNumber);
            FindImages(reader, dictionary);
        }
    }
}