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

The following examples show how to use com.itextpdf.text.pdf.PdfReader#getNumberOfPages() . 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 cover all content using a white rectangle.
 * </p>
 */
@Test
public void testHideContenUnderRectangle() throws IOException, DocumentException
{
    try (   InputStream resource = getClass().getResourceAsStream("document.pdf");
            OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "document-hiddenContent.pdf")))
    {
        PdfReader pdfReader = new PdfReader(resource);
        PdfStamper pdfStamper = new PdfStamper(pdfReader, result);
        for (int page = 1; page <= pdfReader.getNumberOfPages(); page++)
        {
            Rectangle pageSize = pdfReader.getPageSize(page);
            PdfContentByte canvas = pdfStamper.getOverContent(page);
            canvas.setColorFill(BaseColor.WHITE);
            canvas.rectangle(pageSize.getLeft(), pageSize.getBottom(), pageSize.getWidth(), pageSize.getHeight());
            canvas.fill();
        }
        pdfStamper.close();
    }
}
 
Example 2
Source File: EditPageContent.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testIdentity20150211600() throws IOException, DocumentException
{
    try (   InputStream resource = getClass().getResourceAsStream("/mkl/testarea/itext5/extract/20150211600.PDF");
            OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "20150211600-identity.pdf")))
    {
        PdfReader pdfReader = new PdfReader(resource);
        PdfStamper pdfStamper = new PdfStamper(pdfReader, result);
        PdfContentStreamEditor identityEditor = new PdfContentStreamEditor();

        for (int i = 1; i <= pdfReader.getNumberOfPages(); i++)
        {
            identityEditor.editPage(pdfStamper, i);
        }
        
        pdfStamper.close();
    }
}
 
Example 3
Source File: EditPageContent.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testIdentityTest3() throws IOException, DocumentException
{
    try (   InputStream resource = getClass().getResourceAsStream("test3.pdf");
            OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "test3-identity.pdf")))
    {
        PdfReader pdfReader = new PdfReader(resource);
        PdfStamper pdfStamper = new PdfStamper(pdfReader, result);
        PdfContentStreamEditor identityEditor = new PdfContentStreamEditor();

        for (int i = 1; i <= pdfReader.getNumberOfPages(); i++)
        {
            identityEditor.editPage(pdfStamper, i);
        }
        
        pdfStamper.close();
    }
}
 
Example 4
Source File: ExtractDrawnCheckboxes.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/40549977/reading-legacy-word-forms-checkboxes-converted-to-pdf">
 * Reading legacy Word forms checkboxes converted to PDF
 * </a>
 * <br>
 * <a href="https://www.dropbox.com/s/4z7ky3yy2yaj53i/Doc1.pdf?dl=0">
 * Doc1.pdf
 * </a>
 * <p>
 * This test shows how one can extract the sample drawn "checkboxes" from the
 * sample PDF provided by the OP.
 * </p>
 */
@Test
public void testExtractDoc1() throws IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("Doc1.pdf"))
    {
        PdfReader pdfReader = new PdfReader(resource);

        for (int page = 1; page <= pdfReader.getNumberOfPages(); page++)
        {
            System.out.printf("\nPage %s\n====\n", page);

            CheckBoxExtractionStrategy strategy = new CheckBoxExtractionStrategy();
            PdfReaderContentParser parser = new PdfReaderContentParser(pdfReader);
            parser.processContent(page, strategy);

            for (Box box : strategy.getBoxes())
            {
                Vector basePoint = box.getDiagonal().getStartPoint();
                System.out.printf("at %s, %s - %s\n", basePoint.get(Vector.I1), basePoint.get(Vector.I2),
                        box.isChecked() ? "checked" : "unchecked");
            }
        }
    }
}
 
Example 5
Source File: PdfVeryDenseMergeTool.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
void merge(PdfReader reader) throws IOException
{
    PdfReaderContentParser parser = new PdfReaderContentParser(reader);
    for (int page = 1; page <= reader.getNumberOfPages(); page++)
    {
        merge(reader, parser, page);
    }
}
 
Example 6
Source File: PdfDenseMergeTool.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
void merge(PdfReader reader) throws IOException
{
    PdfReaderContentParser parser = new PdfReaderContentParser(reader);
    for (int page = 1; page <= reader.getNumberOfPages(); page++)
    {
        merge(reader, parser, page);
    }
}
 
Example 7
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 8
Source File: CropManager.java    From Briss-2.0 with GNU General Public License v3.0 5 votes vote down vote up
public static CropJob createCropJob(ClusterJob curClusterJob) throws IOException {
    File source = curClusterJob.getSource();
    if (source != null && source.exists()) {
        PdfReader reader = new PdfReader(source.getAbsolutePath());
        CropJob result = new CropJob(source, reader.getNumberOfPages(), reader.getInfo(),
            SimpleBookmark.getBookmark(reader));
        reader.close();
        result.setClusterCollection(curClusterJob.getClusterCollection());
        return result;
    }
    return null;
}
 
Example 9
Source File: TextExtraction.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/37748346/extract-text-with-itext-not-works-encoding-or-crypted-text">
 * Extract text with iText not works: encoding or crypted text?
 * </a>
 * <br/>
 * <a href="https://dl.dropboxusercontent.com/u/6413030/pb.pdf">
 * pb.pdf
 * </a>
 * <p>
 * The document has not been provided by the OP but by
 * <a href="http://stackoverflow.com/users/1127485/sschuberth">sschuberth</a>
 * in a comment.
 * </p>
 * <p>
 * In contrast to {@link #testPb()}, we here first remove the <b>ToUnicode</b>
 * tables of the fonts. And indeed, now extraction succeeds.
 * </p>
 */
@Test
public void testPbNoToUnicode() throws Exception
{
    InputStream resourceStream = getClass().getResourceAsStream("pb.pdf");
    try
    {
        PdfReader reader = new PdfReader(resourceStream);
        for (int i = 1; i <= reader.getNumberOfPages(); i++)
        {
            PdfDictionary pageResources = reader.getPageResources(i);
            if (pageResources == null)
                continue;
            PdfDictionary pageFonts = pageResources.getAsDict(PdfName.FONT); 
            if (pageFonts == null)
                continue;
            for (PdfName key : pageFonts.getKeys())
            {
                PdfDictionary fontDictionary = pageFonts.getAsDict(key);
                fontDictionary.put(PdfName.TOUNICODE, null);
            }
        }

        String content = extractAndStore(reader, new File(RESULT_FOLDER, "pb-noToUnicode.%s.txt").toString());

        System.out.println("\nText pb.pdf without ToUnicode\n************************");
        System.out.println(content);
        System.out.println("************************");
    }
    finally
    {
        if (resourceStream != null)
            resourceStream.close();
    }
}
 
Example 10
Source File: WatermarkPdfTests.java    From kbase-doc with Apache License 2.0 5 votes vote down vote up
/**
 * pdf 用文字加水印,存在问题,如何支持中文
 * @author eko.zhan at 2018年9月2日 下午1:44:40
 * @throws FileNotFoundException
 * @throws IOException
 * @throws DocumentException
 */
@Test
public void testVisioAsPdfWithText() throws FileNotFoundException, IOException, DocumentException{
	File inputFile = new File("E:/ConvertTester/TestFiles/I_am_a_vsdx.vsdx");
	File outputFile = new File("E:/ConvertTester/TestFiles/I_am_a_vsdx_libreoffice.pdf");
	if (!outputFile.exists()) {
		convert(inputFile, outputFile);
	}
	File destFile = new File("E:/ConvertTester/TestFiles/I_am_a_vsdx_libreoffice_watermark.pdf");
	//转换成 pdf 后利用 itext 加水印 
	PdfReader reader = new PdfReader(new FileInputStream(outputFile));
	PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destFile));
	int pageNo = reader.getNumberOfPages();
	Font f = new Font(FontFamily.HELVETICA, 28);
	Phrase p = new Phrase("Xiaoi Robot", f);
	for (int i=1;i<=pageNo;i++) {
		PdfContentByte over = stamper.getOverContent(i);
		over.saveState();
		PdfGState gs1 = new PdfGState();
		gs1.setFillOpacity(0.5f);
		over.setGState(gs1);
		ColumnText.showTextAligned(over, Element.ALIGN_CENTER, p, 297, 450, 0);
		over.restoreState();
	}
	stamper.close();
	reader.close();
}
 
Example 11
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 12
Source File: DocumentCropper.java    From Briss-2.0 with GNU General Public License v3.0 5 votes vote down vote up
public PdfMetaInformation(final File source) throws IOException {
    PdfReader reader = new PdfReader(source.getAbsolutePath());
    this.sourcePageCount = reader.getNumberOfPages();
    this.sourceMetaInfo = reader.getInfo();
    this.sourceBookmarks = SimpleBookmark.getBookmark(reader);
    reader.close();

}
 
Example 13
Source File: SmartMerging.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
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;
}
 
Example 14
Source File: AbstractPdfPageSplittingTool.java    From testarea-itext5 with GNU Affero General Public License v3.0 4 votes vote down vote up
void split(PdfReader reader) throws IOException {
    for (int page = 1; page <= reader.getNumberOfPages(); page++) {
        split(reader, page);
    }
}
 
Example 15
Source File: ChangeTextColor.java    From testarea-itext5 with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/40401800/traverse-whole-pdf-and-change-some-attribute-with-some-object-in-it-using-itext">
 * Traverse whole PDF and change some attribute with some object in it using iText
 * </a>
 * <p>
 * This test shows how to change the color of text of a given color. In this case,
 * black text is changed to green.
 * </p>
 * <p>
 * Beware, this is a proof-of-concept, not a final and complete solution. In particular
 * </p>
 * <ul>
 * <li>Text is considered to be black if for its <code>color</code> the expression
 * <code>BaseColor.BLACK.equals(color)</code> is <code>true</code>; as equality among
 * <code>BaseColor</code> and its descendant classes is not completely well-defined,
 * this might lead to some false positives.
 * <li><code>PdfContentStreamEditor</code> only inspects and edits the content
 * stream of the page itself, not the content streams of displayed form xobjects
 * or patterns; thus, some text may not be found.
 * </ul>
 * <p>
 * Improving the class to properly detect black color and to recursively traverse and
 * edit the content streams of used patterns and xobjects remains as an exercise for
 * the reader.
 * </p> 
 */
@Test
public void testChangeBlackTextToGreenDocument() throws IOException, DocumentException
{
    try (   InputStream resource = getClass().getResourceAsStream("document.pdf");
            OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "document-blackTextToGreen.pdf")))
    {
        PdfReader pdfReader = new PdfReader(resource);
        PdfStamper pdfStamper = new PdfStamper(pdfReader, result);
        PdfContentStreamEditor editor = new PdfContentStreamEditor()
        {
            @Override
            protected void write(PdfContentStreamProcessor processor, PdfLiteral operator, List<PdfObject> operands) throws IOException
            {
                String operatorString = operator.toString();

                if (TEXT_SHOWING_OPERATORS.contains(operatorString))
                {
                    if (currentlyReplacedBlack == null)
                    {
                        BaseColor currentFillColor = gs().getFillColor();
                        if (BaseColor.BLACK.equals(currentFillColor))
                        {
                            currentlyReplacedBlack = currentFillColor;
                            super.write(processor, new PdfLiteral("rg"), Arrays.asList(new PdfNumber(0), new PdfNumber(1), new PdfNumber(0), new PdfLiteral("rg")));
                        }
                    }
                }
                else if (currentlyReplacedBlack != null)
                {
                    if (currentlyReplacedBlack instanceof CMYKColor)
                    {
                        super.write(processor, new PdfLiteral("k"), Arrays.asList(new PdfNumber(0), new PdfNumber(0), new PdfNumber(0), new PdfNumber(1), new PdfLiteral("k")));
                    }
                    else if (currentlyReplacedBlack instanceof GrayColor)
                    {
                        super.write(processor, new PdfLiteral("g"), Arrays.asList(new PdfNumber(0), new PdfLiteral("g")));
                    }
                    else
                    {
                        super.write(processor, new PdfLiteral("rg"), Arrays.asList(new PdfNumber(0), new PdfNumber(0), new PdfNumber(0), new PdfLiteral("rg")));
                    }
                    currentlyReplacedBlack = null;
                }
                
                super.write(processor, operator, operands);
            }

            BaseColor currentlyReplacedBlack = null;

            final List<String> TEXT_SHOWING_OPERATORS = Arrays.asList("Tj", "'", "\"", "TJ");
        };

        for (int i = 1; i <= pdfReader.getNumberOfPages(); i++)
        {
            editor.editPage(pdfStamper, i);
        }
        
        pdfStamper.close();
    }
}
 
Example 16
Source File: RedactText.java    From testarea-itext5 with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
     * <a href="http://stackoverflow.com/questions/43211367/getting-exception-while-redacting-pdf-using-itext">
     * getting exception while redacting pdf using itext
     * </a>
     * <br/>
     * <a href="https://drive.google.com/file/d/0B-zalNTEeIOwM1JJVWctcW8ydU0/view?usp=drivesdk">
     * edited_120192824_5 (1).pdf
     * </a>
     * <p>
     * Indeed, the PdfClean classes throw a {@link NullPointerException} on page
     * 1 of this PDF. As it turns out, the cause is that the PDF makes use of a
     * construct which according to the PDF specification is obsolete and iText,
     * therefore, chose not to support. 
     * </p>
     */
    @Test
    public void testRedactLikeDevAvitesh() throws DocumentException, IOException
    {
//      InputStream resource = new FileInputStream("D:/itext/edited_120192824_5 (1).pdf");
//      OutputStream result = new FileOutputStream(new File(OUTPUTDIR,
//              "aviteshs.pdf"));

        try (   InputStream resource = getClass().getResourceAsStream("edited_120192824_5 (1).pdf");
                OutputStream result = new FileOutputStream(new File(OUTPUTDIR, "edited_120192824_5 (1)-redacted.pdf")) )
        {
            PdfReader reader = new PdfReader(resource);
            PdfStamper stamper = new PdfStamper(reader, result);
            int pageCount = reader.getNumberOfPages();
            Rectangle linkLocation1 = new Rectangle(440f, 700f, 470f, 710f);
            Rectangle linkLocation2 = new Rectangle(308f, 205f, 338f, 215f);
            Rectangle linkLocation3 = new Rectangle(90f, 155f, 130f, 165f);
            List<PdfCleanUpLocation> cleanUpLocations = new ArrayList<PdfCleanUpLocation>();
            for (int currentPage = 1; currentPage <= pageCount; currentPage++) {
                if (currentPage == 1) {
                    cleanUpLocations.add(new PdfCleanUpLocation(currentPage,
                            linkLocation1, BaseColor.BLACK));
                    cleanUpLocations.add(new PdfCleanUpLocation(currentPage,
                            linkLocation2, BaseColor.BLACK));
                    cleanUpLocations.add(new PdfCleanUpLocation(currentPage,
                            linkLocation3, BaseColor.BLACK));
                } else {
                    cleanUpLocations.add(new PdfCleanUpLocation(currentPage,
                            linkLocation1, BaseColor.BLACK));
                }
            }
            PdfCleanUpProcessor cleaner = new PdfCleanUpProcessor(cleanUpLocations,
                    stamper);
            try {
                cleaner.cleanUp();
            } catch (Exception e) {
                e.printStackTrace();
            }
            stamper.close();
            reader.close();
        }
    }
 
Example 17
Source File: Merging.java    From testarea-itext5 with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
   * <a href="https://stackoverflow.com/questions/46120706/when-i-open-a-pdf-in-adobe-acrobat-pro-dc-the-text-is-getting-messed-up-for-pdf">
   * when i open a pdf in adobe acrobat pro Dc the text is getting messed up for pdf creation i used itext5.5.12
   * </a>
   * <p>
   * Test files "1 Loyds.pdf", "2 CRPWLI.pdf", "3 SLC Dec.pdf", "4 Schedule.pdf",
   * and "5 Sched of INS.pdf" were received via e-mail from Kishore Rachakonda
   * ([email protected]) on 2017-09-11 17:31.
   * </p>
   * <p>
   * This test is a port of the Ruby-on-Rails merge routine provided by the OP.
   * The result does not have the problem described by the OP.
   * </p>
   * <p>
   * Later it became clear that the OP's merge result was post-processed by at
   * least two other programs, and one of those post processors appears to have
   * optimized the use of embedded fonts. Unfortunately "5 Sched of INS.pdf" is
   * not a completely valid PDF: It uses an embedded subset of a font but does
   * not mark the font name accordingly. Thus, the optimizing post processor
   * added this mere font subset (assuming it to be the whole font program) to
   * font resources which require glyphs missing in the subset.
   * </p> 
   */
  @Test
  public void testMergeLikeKishoreSagar() throws IOException, DocumentException {
      try (   InputStream resource1 = getClass().getResourceAsStream("1 Loyds.pdf");
              InputStream resource2 = getClass().getResourceAsStream("2 CRPWLI.pdf");
              InputStream resource3 = getClass().getResourceAsStream("3 SLC Dec.pdf");
              InputStream resource4 = getClass().getResourceAsStream("4 Schedule.pdf");
              InputStream resource5 = getClass().getResourceAsStream("5 Sched of INS.pdf");
              OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "mergeLikeKishoreSagar.pdf"))) {
          InputStream[] pdf_files = {resource1, resource2, resource3, resource4, resource5};

          Document doc = new Document();
          PdfCopy pdf_copy = new PdfCopy(doc, result);
          doc.open();
          
          for (InputStream pdf : pdf_files) {
              PdfReader reader = new PdfReader(pdf);
              int pages = reader.getNumberOfPages();
              for (int p = 1; p <= pages; p++)
                  pdf_copy.addPage(pdf_copy.getImportedPage(reader, p));
              reader.close();
          }

          doc.close();
      }

      /* ported from the original:
doc =Document.new
pdf_copy = PdfCopy.new(doc, FileStream.new(@output_filename))
doc.open
@pdf_files.each do |pdf|
  reader = PdfReader.new(pdf)
  pages = reader.getNumberOfPages()
  (1..pages).each do |p|
    pdf_copy.addPage(pdf_copy.getImportedPage(reader, p))
  end
  reader.close
end
doc.close
       */
  }
 
Example 18
Source File: WatermarkPdfTests.java    From kbase-doc with Apache License 2.0 4 votes vote down vote up
/**
 * pdf 用图片加水印
 * @author eko.zhan at 2018年9月2日 下午1:44:58
 * @throws FileNotFoundException
 * @throws IOException
 * @throws DocumentException
 */
@Test
public void testVisioAsPdfWithImg() throws FileNotFoundException, IOException, DocumentException{
	File inputFile = new File("E:/ConvertTester/TestFiles/I_am_a_vsdx.vsdx");
	File outputFile = new File("E:/ConvertTester/TestFiles/I_am_a_vsdx_libreoffice.pdf");
	if (!outputFile.exists()) {
		convert(inputFile, outputFile);
	}
	File destFile = new File("E:/ConvertTester/TestFiles/I_am_a_vsdx_libreoffice_watermark.pdf");
	final String IMG = "D:\\Xiaoi\\logo\\logo.png";
	//转换成 pdf 后利用 itext 加水印 
	PdfReader reader = new PdfReader(new FileInputStream(outputFile));
	PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destFile));
	int pageNo = reader.getNumberOfPages();
	// text watermark
	Font f = new Font(FontFamily.HELVETICA, 30);
	Phrase p = new Phrase("Xiaoi Robot Image", f);
	// image watermark
	Image img = Image.getInstance(IMG);
	float w = img.getScaledWidth();
	float h = img.getScaledHeight();
	// transparency
	PdfGState gs1 = new PdfGState();
	gs1.setFillOpacity(0.5f);
	// properties
	PdfContentByte over;
	Rectangle pagesize;
	float x, y;
	// loop over every page
	for (int i = 1; i <= pageNo; 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);
		if (i % 2 == 1)
			ColumnText.showTextAligned(over, Element.ALIGN_CENTER, p, x, y, 0);
		else
			over.addImage(img, w, 0, 0, h, x - (w / 2), y - (h / 2));
		over.restoreState();
	}
	stamper.close();
	reader.close();
}
 
Example 19
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);
        }
    }
}
 
Example 20
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()}));
    }
}