com.itextpdf.text.DocumentException Java Examples

The following examples show how to use com.itextpdf.text.DocumentException. 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: StampColoredText.java    From testarea-itext5 with GNU Affero General Public License v3.0 9 votes vote down vote up
/**
 * The OP's original code transformed into Java
 */
void stampTextOriginal(InputStream source, OutputStream target) throws DocumentException, IOException
{
    Date today = new Date();
    PdfReader reader = new PdfReader(source);
    PdfStamper stamper = new PdfStamper(reader, target);
    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, BaseFont.EMBEDDED);
    int tSize = 24;
    String mark = "DRAFT " + today;
    int angle = 45;
    float height = reader.getPageSizeWithRotation(1).getHeight()/2;
    float width = reader.getPageSizeWithRotation(1).getWidth()/2;
    PdfContentByte cb = stamper.getOverContent(1);
    cb.setColorFill(new BaseColor(255,200,200));
    cb.setFontAndSize(bf, tSize);
    cb.beginText();
    cb.showTextAligned(Element.ALIGN_CENTER, mark, width, height, angle);
    cb.endText();
    stamper.close();
    reader.close();
}
 
Example #2
Source File: CreateSignature.java    From testarea-itext5 with GNU Affero General Public License v3.0 7 votes vote down vote up
@Test
public void signCertify2gNoAppend() throws IOException, DocumentException, GeneralSecurityException
{
    String filepath = "src/test/resources/mkl/testarea/itext5/signature/2g.pdf";
    String digestAlgorithm = "SHA512";
    CryptoStandard subfilter = CryptoStandard.CMS;

    // Creating the reader and the stamper
    PdfReader reader = new PdfReader(filepath, null, true);
    FileOutputStream os = new FileOutputStream(new File(RESULT_FOLDER, "2g-certified-noAppend.pdf"));
    PdfStamper stamper =
        PdfStamper.createSignature(reader, os, '\0', RESULT_FOLDER);
    // Creating the appearance
    PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    appearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);
    appearance.setReason("reason");
    appearance.setLocation("location");
    appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig");
    // Creating the signature
    ExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm, "BC");
    ExternalDigest digest = new BouncyCastleDigest();
    MakeSignature.signDetached(appearance, digest, pks, chain,
        null, null, null, 0, subfilter);
}
 
Example #3
Source File: PDFUtil.java    From roncoo-education with MIT License 7 votes vote down vote up
/**
 * 水印
 */
public static void setWatermark(MultipartFile src, File dest, String waterMarkName, int permission) throws DocumentException, IOException {
	PdfReader reader = new PdfReader(src.getInputStream());
	PdfStamper stamper = new PdfStamper(reader, new BufferedOutputStream(new FileOutputStream(dest)));
	int total = reader.getNumberOfPages() + 1;
	PdfContentByte content;
	BaseFont base = BaseFont.createFont();
	for (int i = 1; i < total; i++) {
		content = stamper.getOverContent(i);// 在内容上方加水印
		content.beginText();
		content.setTextMatrix(70, 200);
		content.setFontAndSize(base, 30);
		content.setColorFill(BaseColor.GRAY);
		content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 300, 400, 45);
		content.endText();
	}
	stamper.close();
}
 
Example #4
Source File: AnnotationIcons.java    From testarea-itext5 with GNU Affero General Public License v3.0 7 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/46204693/cant-get-itext-rectangle-to-work-correctly-with-annotations">
 * Can't get itext Rectangle to work correctly with annotations
 * </a>
 * <p>
 * This test looks at a <b>Text</b> annotation added via a {@link Chunk}
 * as done by the OP. As this way of adding annotations resets the
 * annotation <b>Rect</b> to the bounding box of the rendered {@link Chunk},
 * it is not really what the OP wants.
 * </p>
 */
@Test
public void testAnnotationIconForTYD() throws FileNotFoundException, DocumentException {
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "annotationIcons.pdf")));
    document.open();

    // Not "new Rectangle(164, 190, 164, 110)" which would be empty
    Rectangle rect = new Rectangle(164, 190, 328, 300);

    // Annotation added like the OP does
    Chunk chunk_text = new Chunk("Let's test a Text annotation...");
    chunk_text.setAnnotation(PdfAnnotation.createText(writer, rect, "Warning", "This is a Text annotation with Comment icon.", false, "Comment"));        

    document.add(chunk_text);

    // Annotation added to the document without Chunk
    writer.addAnnotation(PdfAnnotation.createText(writer, rect, "Warning 2", "This is another Text annotation with Comment icon.", false, "Comment"));

    document.close();
}
 
Example #5
Source File: CreateAndAppendDoc.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/29001852/how-to-create-a-pdf-and-you-then-merge-another-pdf-to-the-same-document-using-it">
 * how to create a PDF and you then merge another pdf to the same document using itext
 * </a>
 * <p>
 * Testing the OP's method with <code>paginate</code> set to <code>true</code>
 * </p>
 */
@Test
public void testAppendPDFsPaginate() throws IOException, DocumentException
{
    try (
            InputStream testA4Stream = getClass().getResourceAsStream("testA4.pdf");
            InputStream fromStream = getClass().getResourceAsStream("from.pdf");
            InputStream prefaceStream = getClass().getResourceAsStream("preface.pdf");
            InputStream type3Stream = getClass().getResourceAsStream("Test_Type3_Problem.pdf");
            FileOutputStream output = new FileOutputStream(new File(RESULT_FOLDER, "appendPdfsPaginate.pdf"));
        )
    {
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, output);
        document.open();
        document.add(new Paragraph("Some content to start with"));
        appendPDFs(Arrays.asList(testA4Stream, fromStream, prefaceStream, type3Stream), writer, document, null, true);
        document.close();
    }
}
 
Example #6
Source File: CreateSignature.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void sign2g() throws IOException, DocumentException, GeneralSecurityException
{
    String filepath = "src/test/resources/mkl/testarea/itext5/signature/2g.pdf";
    String digestAlgorithm = "SHA512";
    CryptoStandard subfilter = CryptoStandard.CMS;

    // Creating the reader and the stamper
    PdfReader reader = new PdfReader(filepath, null, true);
    FileOutputStream os = new FileOutputStream(new File(RESULT_FOLDER, "2g-signed.pdf"));
    PdfStamper stamper =
        PdfStamper.createSignature(reader, os, '\0', RESULT_FOLDER, true);
    // Creating the appearance
    PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    //appearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);
    appearance.setReason("reason");
    appearance.setLocation("location");
    appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig");
    // Creating the signature
    ExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm, "BC");
    ExternalDigest digest = new BouncyCastleDigest();
    MakeSignature.signDetached(appearance, digest, pks, chain,
        null, null, null, 0, subfilter);
}
 
Example #7
Source File: RedactText.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/38278816/remove-header-of-a-pdf-using-itext-pdfcleanupprocessor-does-not-work">
 * Remove header of a pdf using iText PdfCleanUpProcessor does not work
 * </a>
 * <br/>
 * <a href="https://www.dropbox.com/s/4u8vupjqc4st3ib/love.pdf?dl=0">
 * love.pdf
 * </a>
 * <p>
 * Cannot reproduce, I get a <code>org.apache.commons.imaging.ImageReadException: Invalid marker found in entropy data</code>.
 * </p>
 */
@Test
public void testRedactLikeShiranSEkanayake() throws IOException, DocumentException
{
    try (   InputStream resource = getClass().getResourceAsStream("love.pdf");
            OutputStream result = new FileOutputStream(new File(OUTPUTDIR, "love-redacted.pdf")) )
    {
        PdfReader reader = new PdfReader(resource);
        PdfStamper stamper = new PdfStamper(reader, result);
        List<PdfCleanUpLocation> cleanUpLocations = new ArrayList<PdfCleanUpLocation>();

        for(int i=1; i<=reader.getNumberOfPages(); i++)
        {
                //System.out.println(i);
                Rectangle mediabox = reader.getPageSize(i); 
                cleanUpLocations.add(new PdfCleanUpLocation(i, new Rectangle(0,800,1000,1000)));
        }
        PdfCleanUpProcessor cleaner = new PdfCleanUpProcessor(cleanUpLocations, stamper);
        cleaner.cleanUp();
        stamper.close();
        reader.close(); 
    }
}
 
Example #8
Source File: PortfolioFileExtraction.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
static Map<Integer, File> retrieveFolders(PdfReader reader, File baseDir) throws DocumentException
{
    Map<Integer, File> result = new HashMap<Integer, File>();

    PdfDictionary root = reader.getCatalog();
    PdfDictionary collection = root.getAsDict(PdfName.COLLECTION);
    if (collection == null)
        throw new DocumentException("Document has no Collection dictionary");
    PdfDictionary folders = collection.getAsDict(FOLDERS);
    if (folders == null)
        throw new DocumentException("Document collection has no folders dictionary");
    
    collectFolders(result, folders, baseDir);

    return result;
}
 
Example #9
Source File: SmartMerging.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/32267542/pdf-merge-issue-in-itextsharp-pdf-looks-distorted-after-merge">
 * Pdf Merge issue in itextsharp - PDF looks distorted after Merge
 * </a>
 * <br>
 * <a href="https://www.dropbox.com/s/l479kvar16p9p57/input.pdf?dl=0">
 * input.pdf
 * </a>
 * <p>
 * This test method together with the static methods {@link #ExtractPages(String, int, int)}
 * and {@link #Merge(File[])} constitute a fairly 1:1 translation of the OP's C#/iTextSharp
 * code. Unfortunately, though, it does not reproduce the error reproducibly occurring in the
 * iTextSharp version.
 * </p>
 */
@Test
public void testSplitAndRemerge() throws IOException, DocumentException
{
    String inputDocPath = "input.pdf";

    byte[] part1 = ExtractPages(inputDocPath, 1, 2);
    File outputPath1 = new File(RESULT_FOLDER, "part1.pdf");
    Files.write(outputPath1.toPath(), part1);

    byte[] part2 = ExtractPages(inputDocPath, 3, 0);
    File outputPath2 = new File(RESULT_FOLDER, "part2.pdf");
    Files.write(outputPath2.toPath(), part2);

    byte[] merged = Merge(new File[] { outputPath1, outputPath2 });

    File mergedPath = new File(RESULT_FOLDER, "output.pdf");
    Files.write(mergedPath.toPath(), merged);
}
 
Example #10
Source File: EditPageContent.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testRemoveTransparentGraphicsTest3() throws IOException, DocumentException
{
    try (   InputStream resource = getClass().getResourceAsStream("test3.pdf");
            OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "test3-noTransparency.pdf")))
    {
        PdfReader pdfReader = new PdfReader(resource);
        PdfStamper pdfStamper = new PdfStamper(pdfReader, result);
        PdfContentStreamEditor editor = new TransparentGraphicsRemover();

        for (int i = 1; i <= pdfReader.getNumberOfPages(); i++)
        {
            editor.editPage(pdfStamper, i);
        }
        
        pdfStamper.close();
    }
}
 
Example #11
Source File: PortfolioFileExtraction.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <p>
 * These two methods ({@link #extractAttachmentsWithFolders(PdfReader, String)} and
 * {@link #extractAttachment(PdfReader, Map, PdfString, PdfDictionary)}) extend the
 * functionality of the OP's original code posted in his question. They extract files
 * with the folder structure.
 * </p>
 * <p>
 * The information concerning the portfolio folder structure is retrieved using
 * the method {@link #retrieveFolders(PdfReader, File)} and its helper method
 * {@link #collectFolders(Map, PdfDictionary, File)}.
 * </p>
 */
public static void extractAttachmentsWithFolders(PdfReader reader, String dir) throws IOException, DocumentException
{
    File folder = new File(dir);
    folder.mkdirs();

    Map<Integer, File> folders = retrieveFolders(reader, folder);

    PdfDictionary root = reader.getCatalog();

    PdfDictionary names = root.getAsDict(PdfName.NAMES);
    System.out.println("" + names.getKeys().toString());
    PdfDictionary embedded = names.getAsDict(PdfName.EMBEDDEDFILES);
    System.out.println("" + embedded.toString());

    PdfArray filespecs = embedded.getAsArray(PdfName.NAMES);

    for (int i = 0; i < filespecs.size();)
    {
        extractAttachment(reader, folders, folder, filespecs.getAsString(i++), filespecs.getAsDict(i++));
    }
}
 
Example #12
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 #13
Source File: CreateTableDirectContent.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
     * <a href="http://stackoverflow.com/questions/43807931/creating-table-in-pdf-on-last-page-bottom-wrong-official-solution">
     * Creating table in pdf on last page bottom (wrong official solution)
     * </a>
     * <p>
     * Helper method for {@link #testCreateTableLikeUser7968180()}.
     * </p>
     */
    private static PdfPTable createFooterTable() throws DocumentException
    {
        int[] columnWidths = new int[] { 1, 1, 1, 1, 1, 1, 1, 1, 1 };
        PdfPTable datatable = new PdfPTable(columnWidths.length);
        datatable.setKeepTogether(true);
        datatable.setWidthPercentage(100);
        datatable.setWidths(columnWidths);
        datatable.getDefaultCell().setPadding(5);

//        datatable.getDefaultCell().setHorizontalAlignment(horizontalAlignment);
//        datatable.getDefaultCell().setVerticalAlignment(verticalAlignment);

        for (int i = 0; i < 100; i++)
        {
            datatable.addCell("Přehledová tabulka");
//            addCellToTable(datatable, horizontalAlignmentLeft, verticalAlignmentMiddle, "Přehledová tabulka",
//                    columnWidths.length, 1, fontTypeBold, fontSizeRegular, cellLayout_Bottom);
        }

        return datatable;
    }
 
Example #14
Source File: TextExtraction.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/47869635/extract-text-from-pdf-using-itextsharp-returns-empty-string">
 * Extract text from pdf using itextsharp returns empty string
 * </a>
 * <br/>
 * <a href="https://smlouvy.gov.cz/smlouva/soubor/5376672/Smlouva%20Z%C5%A0%20Komensk%C3%A9ho%2066%20NJ%20-%20pron%C3%A1jem%20u%C4%8Debny.pdf">
 * Smlouva ZŠ Komenského 66 NJ - pronájem učebny.pdf
 * </a>
 * <p>
 * The PDF itself is weird to start with: It appears to have been OCR'ed
 * ignoring the page rotation, i.e. effectively with the content rotated
 * by 180°, so the recognized text is weird. But there also is an issue
 * of iText: It does not properly extract the so recognized text. This
 * probably is due to the font of the text not having a ToUnicode map
 * and furthermore having a mixed single-byte/double-byte encoding.
 * </p>
 */
@Test
public void testSmlouvaZSKomenskeho66NJpronajemucebny() throws IOException, DocumentException
{
    InputStream resourceStream = getClass().getResourceAsStream("Smlouva ZŠ Komenského 66 NJ - pronájem učebny.pdf");
    try
    {
        PdfReader reader = new PdfReader(resourceStream);
        String content = extractAndStoreSimple(reader, new File(RESULT_FOLDER, "Smlouva ZŠ Komenského 66 NJ - pronájem učebny.%s.txt").toString());

        System.out.println("\nText (simple strategy) Smlouva ZŠ Komenského 66 NJ - pronájem učebny.pdf \n************************");
        System.out.println(content);
        System.out.println("************************");
    }
    finally
    {
        if (resourceStream != null)
            resourceStream.close();
    }
}
 
Example #15
Source File: SwingExportUtil.java    From mzmine3 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Writes swing to pdf
 * 
 * @param panel
 * @param fileName
 * @throws DocumentException
 * @throws Exception
 */
public static void writeToPDF(JComponent panel, File fileName)
    throws IOException, DocumentException {
  // print the panel to pdf
  int width = panel.getWidth();
  int height = panel.getHeight();
  logger.info(
      () -> MessageFormat.format("Exporting panel to PDF file (width x height; {0} x {1}): {2}",
          width, height, fileName.getAbsolutePath()));
  Document document = new Document(new Rectangle(width, height));
  PdfWriter writer = null;
  try {
    writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));
    document.open();
    PdfContentByte contentByte = writer.getDirectContent();
    PdfTemplate template = contentByte.createTemplate(width, height);
    Graphics2D g2 = new PdfGraphics2D(contentByte, width, height, new DefaultFontMapper());
    panel.print(g2);
    g2.dispose();
    contentByte.addTemplate(template, 0, 0);
    document.close();
    writer.close();
  } finally {
    if (document.isOpen()) {
      document.close();
    }
  }
}
 
Example #16
Source File: SimpleRedactionTest.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
static byte[] createRotatedImagePdf() throws DocumentException, IOException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, baos);
    document.open();

    PdfContentByte directContent = writer.getDirectContent();

    BufferedImage bim = new BufferedImage(1000, 250, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = bim.createGraphics();
    g2d.setColor(Color.BLUE);
    g2d.fillRect(0, 0, 500, 500);
    g2d.dispose();

    Image image = Image.getInstance(bim, null);
    directContent.addImage(image, 0, 500, -500, 0, 550, 50);

    document.close();

    return baos.toByteArray();
}
 
Example #17
Source File: DividerAndColorAwareTextExtraction.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/31730278/extract-text-from-pdf-between-two-dividers-with-itextsharp">
 * Extract text from PDF between two dividers with ITextSharp
 * </a>
 * <br>
 * <a href="http://www.tjsc.jus.br/institucional/diario/a2015/20150211600.PDF">
 * 20150211600.PDF
 * </a>
 * <p>
 * This test applies the {@link DividerAndColorAwareTextExtractionStrategy} to the OP's sample
 * document, page 346, to demonstrate its use.
 * </p>
 */
@Test
public void test20150211600_346() throws IOException, DocumentException {
    InputStream resourceStream = getClass().getResourceAsStream("20150211600.PDF");
    BaseColor headerColor = new CMYKColor(0.58f, 0.17f, 0, 0.56f);
    try {
        PdfReader reader = new PdfReader(resourceStream);
        String content = extractAndStore(reader, new File(RESULT_FOLDER, "20150211600.%s.%s.txt").toString(), 346, 346, headerColor);

        System.out.println("\nText 20150211600.PDF\n************************");
        System.out.println(content);
        System.out.println("************************");
    } finally {
        if (resourceStream != null)
            resourceStream.close();
    }
}
 
Example #18
Source File: SplitSmart.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
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;
}
 
Example #19
Source File: TextExtraction.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/32014589/how-to-read-data-from-table-structured-pdf-using-itextsharp">
 * How to read data from table-structured PDF using itextsharp?
 * </a>
 * <br/>
 * <a href="https://www.dropbox.com/s/jwsuu6mz9ez84ss/sampleFile.pdf?dl=0">
 * sampleFile.pdf
 * </a>
 * <p>
 * By explicitly using the {@link SimpleTextExtractionStrategy} one gets the same text
 * as with PDFBox.
 * </p>
 * 
 * @see mkl.testarea.pdfbox1.extract.ExtractText
 */
@Test
public void testSampleFile() throws IOException, DocumentException
{
    InputStream resourceStream = getClass().getResourceAsStream("sampleFile.pdf");
    try
    {
        PdfReader reader = new PdfReader(resourceStream);
        String content = extractAndStoreSimple(reader, new File(RESULT_FOLDER, "sampleFile.%s.txt").toString());

        System.out.println("\nText (simple strategy) sampleFile.pdf \n************************");
        System.out.println(content);
        System.out.println("************************");
    }
    finally
    {
        if (resourceStream != null)
            resourceStream.close();
    }
}
 
Example #20
Source File: TextExtraction.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/32815291/itextsharp-cant-read-numbers-in-this-pdf">
 * iTextSharp can't read numbers in this PDF
 * </a>
 * <br/>
 * <a href="http://www.bnpparibas-ip.sg/doc/fact/FACTSHEET05ENSG07100715FO02332302.pdf">
 * FACTSHEET05ENSG07100715FO02332302.pdf
 * </a>
 * <p>
 * Indeed, neither iText nor iTextSharp could extract certain digits at the time
 * of that question. Meanwhile, though, the issue seems fixed.
 * </p>
 */
@Test
public void testFACTSHEET05ENSG07100715FO02332302() throws IOException, DocumentException
{
    InputStream resourceStream = getClass().getResourceAsStream("FACTSHEET05ENSG07100715FO02332302.pdf");
    try
    {
        PdfReader reader = new PdfReader(resourceStream);
        String content = extractAndStoreSimple(reader, new File(RESULT_FOLDER, "FACTSHEET05ENSG07100715FO02332302.%s.txt").toString());

        System.out.println("\nText FACTSHEET05ENSG07100715FO02332302.pdf\n************************");
        System.out.println(content);
        System.out.println("************************");
    }
    finally
    {
        if (resourceStream != null)
            resourceStream.close();
    }
}
 
Example #21
Source File: AppearanceAndRotation.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
PdfAnnotation createAnnotation(PdfWriter writer, Rectangle rect, String contents) throws DocumentException, IOException {
    PdfContentByte cb = writer.getDirectContent();
    PdfAppearance cs = cb.createAppearance(rect.getWidth(), rect.getHeight());

    cs.rectangle(0 , 0, rect.getWidth(), rect.getHeight());
    cs.fill();

    cs.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED), 12);                        
    cs.beginText();
    cs.setLeading(12 + 1.75f);
    cs.moveText(.75f, rect.getHeight() - 12 + .75f);
    cs.showText(contents);
    cs.endText();

    return PdfAnnotation.createFreeText(writer, rect, contents, cs);
}
 
Example #22
Source File: RotateLink.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testOPCode() throws IOException, DocumentException
{
    try (   InputStream resourceStream = getClass().getResourceAsStream("/mkl/testarea/itext5/merge/testA4.pdf");
            OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "testA4-annotate.pdf"))    )
    {
        PdfReader reader = new PdfReader(resourceStream);
        PdfStamper stamper = new PdfStamper(reader, outputStream);

        Rectangle linkLocation = new Rectangle( 100, 700, 100 + 200, 700 + 25 );
        PdfName highlight = PdfAnnotation.HIGHLIGHT_INVERT;
        PdfAnnotation linkRed  = PdfAnnotation.createLink( stamper.getWriter(), linkLocation, highlight, "red" );
        PdfAnnotation linkGreen = PdfAnnotation.createLink( stamper.getWriter(), linkLocation, highlight, "green" );
        BaseColor baseColorRed = new BaseColor(255,0,0);
        BaseColor baseColorGreen = new BaseColor(0,255,0);
        linkRed.setColor(baseColorRed);
        linkGreen.setColor(baseColorGreen);
        double angleDegrees = 10;
        double angleRadians = Math.PI*angleDegrees/180;
        stamper.addAnnotation(linkRed, 1);
        linkGreen.applyCTM(AffineTransform.getRotateInstance(angleRadians));
        stamper.addAnnotation(linkGreen, 1);
        stamper.close();
    }
}
 
Example #23
Source File: CreateEllipse.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/43205385/trying-to-draw-an-ellipse-annotation-and-the-border-on-the-edges-goes-thin-and-t">
 * Trying to draw an ellipse annotation and the border on the edges goes thin and thik when i try to roatate pdf itext5
 * </a>
 * <p>
 * This test creates an ellipse annotation without appearance on a page without rotation. Everything looks ok.
 * </p>
 * @see #testCreateEllipseAppearance()
 * @see #testCreateEllipseOnRotated()
 * @see #testCreateEllipseAppearanceOnRotated()
 * @see #testCreateCorrectEllipseAppearanceOnRotated()
 */
@Test
public void testCreateEllipse() throws IOException, DocumentException
{
    try (   InputStream resourceStream = getClass().getResourceAsStream("/mkl/testarea/itext5/merge/testA4.pdf");
            OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "testA4-ellipse.pdf"))    )
    {
        PdfReader reader = new PdfReader(resourceStream);
        PdfStamper stamper = new PdfStamper(reader, outputStream);

        Rectangle rect = new Rectangle(202 + 6f, 300, 200 + 100, 300 + 150);

        PdfAnnotation annotation = PdfAnnotation.createSquareCircle(stamper.getWriter(), rect, null, false);
        annotation.setFlags(PdfAnnotation.FLAGS_PRINT);
        annotation.setColor(BaseColor.RED);
        annotation.setBorderStyle(new PdfBorderDictionary(3.5f, PdfBorderDictionary.STYLE_SOLID));

        stamper.addAnnotation(annotation, 1);

        stamper.close();
        reader.close();
    }
}
 
Example #24
Source File: CreateEllipse.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/43205385/trying-to-draw-an-ellipse-annotation-and-the-border-on-the-edges-goes-thin-and-t">
 * Trying to draw an ellipse annotation and the border on the edges goes thin and thik when i try to roatate pdf itext5
 * </a>
 * <p>
 * This test creates an ellipse annotation without appearance on a page with rotation.
 * The ellipse form looks ok but it is moved to the right of the actual appearance rectangle when viewed in Adobe Reader.
 * This is caused by iText creating a non-standard rectangle, the lower left not being the lower left etc.
 * </p>
 * @see #testCreateEllipse()
 * @see #testCreateEllipseAppearance()
 * @see #testCreateEllipseAppearanceOnRotated()
 * @see #testCreateCorrectEllipseAppearanceOnRotated()
 */
@Test
public void testCreateEllipseOnRotated() throws IOException, DocumentException
{
    try (   InputStream resourceStream = getClass().getResourceAsStream("/mkl/testarea/itext5/merge/testA4.pdf");
            OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "testA4-rotated-ellipse.pdf"))    )
    {
        PdfReader reader = new PdfReader(resourceStream);
        reader.getPageN(1).put(PdfName.ROTATE, new PdfNumber(90));

        PdfStamper stamper = new PdfStamper(reader, outputStream);

        Rectangle rect = new Rectangle(202 + 6f, 300, 200 + 100, 300 + 150);

        PdfAnnotation annotation = PdfAnnotation.createSquareCircle(stamper.getWriter(), rect, null, false);
        annotation.setFlags(PdfAnnotation.FLAGS_PRINT);
        annotation.setColor(BaseColor.RED);
        annotation.setBorderStyle(new PdfBorderDictionary(3.5f, PdfBorderDictionary.STYLE_SOLID));

        stamper.addAnnotation(annotation, 1);

        stamper.close();
        reader.close();
    }
}
 
Example #25
Source File: VeryDenseMerging.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/28991291/how-to-remove-whitespace-on-merge">
 * How To Remove Whitespace on Merge
 * </a>
 * <p>
 * Testing {@link PdfVeryDenseMergeTool} using the OP's files.
 * </p>
 */
@Test
public void testMergeGrandizerFiles() throws DocumentException, IOException
{
    try (   InputStream docA = getClass().getResourceAsStream("Header.pdf");
            InputStream docB = getClass().getResourceAsStream("Body.pdf");
            InputStream docC = getClass().getResourceAsStream("Footer.pdf");    )
    {
        PdfVeryDenseMergeTool tool = new PdfVeryDenseMergeTool(PageSize.A4, 18, 18, 5);
        PdfReader readerA = new PdfReader(docA);
        PdfReader readerB = new PdfReader(docB);
        PdfReader readerC = new PdfReader(docC);
        try (FileOutputStream fos = new FileOutputStream(new File(RESULT_FOLDER, "GrandizerMerge-veryDense.pdf")))
        {
            List<PdfReader> inputs = Arrays.asList(readerA, readerB, readerC);
            tool.merge(fos, inputs);
        }
        finally
        {
            readerA.close();
            readerB.close();
            readerC.close();
        }
    }
}
 
Example #26
Source File: ImportPageWithoutFreeSpace.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * This method creates a PDF with a single styled paragraph.
 */
static byte[] createSimpleCircleGraphicsPdf() throws DocumentException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, baos);
    document.open();

    float y = writer.getPageSize().getTop(document.topMargin());
    float radius = 20;
    for (int i = 0; i < 3; i++)
    {
        Rectangle pageSize = writer.getPageSize();
        writer.getDirectContent().circle(
                pageSize.getLeft(document.leftMargin()) + (pageSize.getWidth() - document.leftMargin() - document.rightMargin()) * Math.random(),
                y-radius, radius);
        y-= 2*radius + 5;
    }

    writer.getDirectContent().fillStroke();
    document.close();

    return baos.toByteArray();
}
 
Example #27
Source File: CreateSignature.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
public void C2_01_SignHelloWorld_sign(String src, String dest, Certificate[] chain, PrivateKey pk, String digestAlgorithm, String provider, CryptoStandard subfilter, String reason, String location)
        throws GeneralSecurityException, IOException, DocumentException {
    // Creating the reader and the stamper
    PdfReader reader = new PdfReader(src);
    FileOutputStream os = new FileOutputStream(dest);
    PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
    // Creating the appearance
    PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    appearance.setReason(reason);
    appearance.setLocation(location);
    appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig");
    // Creating the signature
    ExternalDigest digest = new BouncyCastleDigest();
    ExternalSignature signature = new PrivateKeySignature(pk, digestAlgorithm, provider);
    MakeSignature.signDetached(appearance, digest, signature, chain, null, null, null, 0, subfilter);
}
 
Example #28
Source File: DenseMerging.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
static byte[] createSimpleTextPdf(String paragraphFormat, int paragraphCount) throws DocumentException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter.getInstance(document, baos);
    document.open();
    for (int i = 0; i < paragraphCount; i++)
    {
        Paragraph paragraph = new Paragraph();
        paragraph.add(String.format(paragraphFormat, i));
        document.add(paragraph);
    }
    document.close();

    return baos.toByteArray();
}
 
Example #29
Source File: ColorParagraphBackground.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testParagraphBackgroundEventListener() throws DocumentException, FileNotFoundException
{
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "document-with-paragraph-backgrounds.pdf")));
    ParagraphBackground border = new ParagraphBackground();
    writer.setPageEvent(border);
    document.open();
    document.add(new Paragraph("Hello,"));
    document.add(new Paragraph("In this document, we'll add several paragraphs that will trigger page events. As long as the event isn't activated, nothing special happens, but let's make the event active and see what happens:"));
    border.setActive(true);
    document.add(new Paragraph("This paragraph now has a background. Isn't that fantastic? By changing the event, we can even draw a border, change the line width of the border and many other things. Now let's deactivate the event."));
    border.setActive(false);
    document.add(new Paragraph("This paragraph no longer has a background."));
    document.close();
}
 
Example #30
Source File: VeryDenseMerging.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
static byte[] createSimpleTextPdf(String paragraphFormat, int paragraphCount) throws DocumentException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter.getInstance(document, baos);
    document.open();
    for (int i = 0; i < paragraphCount; i++)
    {
        Paragraph paragraph = new Paragraph();
        paragraph.add(String.format(paragraphFormat, i));
        document.add(paragraph);
    }
    document.close();

    return baos.toByteArray();
}