Java Code Examples for com.itextpdf.text.pdf.PdfStamper#close()

The following examples show how to use com.itextpdf.text.pdf.PdfStamper#close() . 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: EditPageContent.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testRemoveTransparentGraphicsTransparency() throws IOException, DocumentException
{
    try (   InputStream resource = getClass().getResourceAsStream("transparency.pdf");
            OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "transparency-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 3
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 4
Source File: PDFUtil.java    From pdf-bookmark with MIT License 6 votes vote down vote up
private static void addOutlines(List<HashMap<String, Object>> outlines, String srcFile, String destFile) {
    try {
        class MyPdfReader extends PdfReader {
            public MyPdfReader(String fileName) throws IOException {
                super(fileName);
                unethicalreading = true;
                encrypted = false;
            }
        }
        PdfReader reader = new MyPdfReader(srcFile);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destFile));
        stamper.setOutlines(outlines);
        stamper.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 5
Source File: RedactText.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/44304695/itext-5-5-11-bold-text-looks-blurry-after-using-pdfcleanupprocessor">
 * iText 5.5.11 - bold text looks blurry after using PdfCleanUpProcessor
 * </a>
 * <br/>
 * <a href="http://s000.tinyupload.com/index.php?file_id=52420782334200922303">
 * before.pdf
 * </a>
 * <p>
 * Indeed, the observation by the OP can be reproduced. The issue has been introduced
 * into iText in commits d5abd23 and 9967627, both dated May 4th, 2015.
 * </p>
 */
@Test
public void testRedactLikeTieco() throws DocumentException, IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("before.pdf");
            OutputStream result = new FileOutputStream(new File(OUTPUTDIR, "before-redacted.pdf")) )
    {
        PdfReader reader = new PdfReader(resource);
        PdfStamper stamper = new PdfStamper(reader, result);
        List<PdfCleanUpLocation> cleanUpLocations = new ArrayList<PdfCleanUpLocation>();

        cleanUpLocations.add(new PdfCleanUpLocation(1, new Rectangle(0f, 0f, 595f, 680f)));

        PdfCleanUpProcessor cleaner = new PdfCleanUpProcessor(cleanUpLocations, stamper);
        cleaner.cleanUp();

        stamper.close();
        reader.close();
    }
}
 
Example 6
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 7
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 8
Source File: RedactText.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/35374912/itext-cleaning-up-text-in-rectangle-without-cleaning-full-row">
 * iText - Cleaning Up Text in Rectangle without cleaning full row
 * </a>
 * <br/>
 * <a href="https://www.dropbox.com/s/3i7g4w85dvul6db/input.pdf?dl=0">
 * input.pdf
 * </a>
 * <p>
 * Cannot reproduce the OP's issue.
 * </p>
 */
@Test
public void testRedactJavishsInput() throws IOException, DocumentException
{
    try (   InputStream resource = getClass().getResourceAsStream("input.pdf");
            OutputStream result = new FileOutputStream(new File(OUTPUTDIR, "input-redactedJavish.pdf")) )
    {
        PdfReader reader = new PdfReader(resource);
        PdfStamper stamper = new PdfStamper(reader, result);

        List<Float> linkBounds = new ArrayList<Float>();
        linkBounds.add(0, (float) 200.7);
        linkBounds.add(1, (float) 547.3);
        linkBounds.add(2, (float) 263.3);
        linkBounds.add(3, (float) 558.4);

        Rectangle linkLocation1 = new Rectangle(linkBounds.get(0), linkBounds.get(1), linkBounds.get(2), linkBounds.get(3));
        List<PdfCleanUpLocation> cleanUpLocations = new ArrayList<PdfCleanUpLocation>();
        cleanUpLocations.add(new PdfCleanUpLocation(1, linkLocation1, BaseColor.GRAY));

        PdfCleanUpProcessor cleaner = new PdfCleanUpProcessor(cleanUpLocations, stamper);
        cleaner.cleanUp();

        stamper.close();
        reader.close();
    }
}
 
Example 9
Source File: CreateEllipse.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 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 with appearance with switched dimensions on a page with rotation.
 * Everything looks ok.
 * </p>
 * @see #testCreateEllipse()
 * @see #testCreateEllipseAppearance()
 * @see #testCreateEllipseOnRotated()
 * @see #testCreateEllipseAppearanceOnRotated()
 */
@Test
public void testCreateCorrectEllipseAppearanceOnRotated() 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-appearance-correct.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));

        PdfContentByte cb = stamper.getOverContent(1);
        PdfAppearance app = cb.createAppearance(rect.getHeight(), rect.getWidth());
        app.setColorStroke(BaseColor.RED);
        app.setLineWidth(3.5);
        app.ellipse( 1.5,  1.5, rect.getHeight() - 1.5, rect.getWidth() - 1.5);
        app.stroke();
        annotation.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, app);

        stamper.addAnnotation(annotation, 1);

        stamper.close();
        reader.close();
    }
}
 
Example 10
Source File: RedactText.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/38053804/itextsharp-cropping-pdf-with-images-throws-exception">
 * iTextSharp - Cropping PDF with images throws exception
 * </a>
 * <br/>
 * <a href="https://www.dropbox.com/s/i76q8j1n5b0kdtv/1.pdf?dl=0">
 * 1.pdf
 * </a>, as Narek-1.pdf here
 * <p>
 * Indeed, there is an exception reading this image from PDF.
 * </p>
 */
@Test
public void testRedactNarek_1() throws IOException, DocumentException
{
    try (   InputStream resource = getClass().getResourceAsStream("Narek-1.pdf");
            OutputStream result = new FileOutputStream(new File(OUTPUTDIR, "Narek-1-redacted.pdf")) )
    {
        PdfReader reader = new PdfReader(resource);
        PdfStamper stamper = new PdfStamper(reader, result);
        redactLikeNarek(stamper);
        stamper.close();
    }
}
 
Example 11
Source File: EditPageContent.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/38498431/how-to-remove-filtered-content-from-a-pdf-with-itext">
 * How to remove filtered content from a PDF with iText
 * </a>
 * <br/>
 * <a href="https://1drv.ms/b/s!AmNST-TRoPSemi2k0UnGFsjQM1Yt">
 * document.pdf
 * </a>
 * <p>
 * This test shows how to remove text filtered by font size. The filter
 * condition given by the OP, i.e. any text drawn using a font whose
 * name ends with "BoldMT", had turned out to match more often than
 * desired, cf. {@link #testRemoveBoldMTTextDocument()}.
 * </p>
 */
@Test
public void testRemoveBigTextDocument() throws IOException, DocumentException
{
    try (   InputStream resource = getClass().getResourceAsStream("document.pdf");
            OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "document-noBigText.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 (gs().getFontSize() > 100)
                        return;
                }
                
                super.write(processor, operator, operands);
            }

            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 12
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 13
Source File: Stamping.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/41183349/pdf-file-size-is-largely-increased-when-copied-using-itext-java-library">
 * pdf file size is largely increased when copied using itext java library
 * </a>
 * <br/>
 * <a href="https://www.pdfill.com/download/AcroJS.pdf">
 * AcroJS.pdf
 * </a>
 * <p>
 * Using full compression is much more compressed than the original.
 * </p>
 */
@Test
public void testStampAcroJSCompressed() throws DocumentException, IOException
{
    try (   InputStream resourceStream = getClass().getResourceAsStream("AcroJS.pdf");
            OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "AcroJS-stamped-compressed.pdf"))    )
    {
        PdfReader reader = new PdfReader(resourceStream);
        PdfStamper stamper = new PdfStamper(reader, outputStream);
        stamper.setFullCompression();

        stamper.close();
    }
}
 
Example 14
Source File: EditPageContent.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/38498431/how-to-remove-filtered-content-from-a-pdf-with-itext">
 * How to remove filtered content from a PDF with iText
 * </a>
 * <br/>
 * <a href="https://1drv.ms/b/s!AmNST-TRoPSemi2k0UnGFsjQM1Yt">
 * document.pdf
 * </a>
 * <p>
 * This test shows how to remove text matching the filter condition given
 * by the OP, i.e. any text drawn using a font whose name ends with "BoldMT".
 * </p>
 * <p>
 * This works well, too good actually, as some table headers also use a
 * "BoldMT" font and, therefore, also vanish. As an alternative look at
 * {@link #testRemoveBigTextDocument()} which simply uses the font size
 * as filter condition.
 * </p>
 */
@Test
public void testRemoveBoldMTTextDocument() throws IOException, DocumentException
{
    try (   InputStream resource = getClass().getResourceAsStream("document.pdf");
            OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "document-noBoldMTText.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 (gs().getFont().getPostscriptFontName().endsWith("BoldMT"))
                        return;
                }
                
                super.write(processor, operator, operands);
            }

            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 15
Source File: FindFreeSpace.java    From testarea-itext5 with GNU Affero General Public License v3.0 4 votes vote down vote up
@Test
public void testOP() throws IOException, DocumentException
{
    System.out.println("\nTHE OP's CODE");

    InputStream resourceStream = getClass().getResourceAsStream("Final PADR Release.pdf");
    try
    {
        // The resulting PDF file
        String RESULT = "target/test-outputs/extract/Final PADR Release 1.pdf";

        // Create a reader
        PdfReader reader = new PdfReader(resourceStream);

        // Create a stamper
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT));

        // Loop over the pages and add a footer to each page
        int n = reader.getNumberOfPages();

        for (int i = 2; i <= n; i++)
        {
            Collection<Rectangle2D> rectangles = find(reader, 300, 100, i); // FIX: i was n before

            Iterator<Rectangle2D> itr = rectangles.iterator();
            while (itr.hasNext())
            {
                System.out.println(itr.next());
            }

            if (!(rectangles.isEmpty()) && (rectangles.size() != 0))
            {
                Rectangle2D best = null;
                double bestDist = Double.MAX_VALUE;

                Point2D.Double point = new Point2D.Double(200, 400);

                float x = 0, y = 0;

                for (Rectangle2D rectangle : rectangles)
                {
                    double distance = distance(rectangle, point);

                    if (distance < bestDist)
                    {
                        best = rectangle;

                        bestDist = distance;

                        x = (float) best.getX();

                        y = (float) best.getMaxY(); // FIX: was getY

                        int left = (int) best.getMinX();

                        int right = (int) best.getMaxX();

                        int top = (int) best.getMaxY();

                        int bottom = (int) best.getMinY();

                        System.out.println("x : " + x);
                        System.out.println("y : " + y);
                        System.out.println("left : " + left);
                        System.out.println("right : " + right);
                        System.out.println("top : " + top);
                        System.out.println("bottom : " + bottom);

                    }
                }

                getFooterTable(i, n).writeSelectedRows(0, -1, x, y, stamper.getOverContent(i));
            }

            else
            {
                System.err.println("No free space found here");
                getFooterTable(i, n).writeSelectedRows(0, -1, 94, 140, stamper.getOverContent(i));
            }
        }

        // Close the stamper
        stamper.close();

        // Close the reader
        reader.close();
    }
    finally
    {
        if (resourceStream != null)
            resourceStream.close();
    }
}
 
Example 16
Source File: AddField.java    From testarea-itext5 with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/32445174/missing-deselected-display-items-at-the-beginning-of-the-list-box-itextsharp">
 * Missing deselected display items at the beginning of the list box (iTextSharp)
 * </a>
 * <br/>
 * <a href="http://stackoverflow.com/questions/37587703/deselected-display-items-missing-at-the-beginning-of-the-list-box-itextsharp">
 * Deselected display items missing at the beginning of the list box (iTextSharp)
 * </a>
 * 
 * <p>
 * This is the equivalent code to the OP's VB .Net code.
 * </p>
 * <p>
 * Indeed, "One" is invisible at first. As a fix, set the VisibleTopChoice.
 * </p>
 */
@Test
public void testAddLikeNickK() throws IOException, DocumentException
{
    File myFile = new File(RESULT_FOLDER, "test-multiSelectBox.pdf");
    
    Rectangle newRect = new Rectangle(231.67f, 108.0f, 395.67f, 197.0f);
    String newFldName = "ListBox1";
    int pg = 1;

    try (   InputStream resource = getClass().getResourceAsStream("/mkl/testarea/itext5/extract/test.pdf");
            OutputStream output = new FileOutputStream(myFile)  )
    {
        PdfReader pdfReader = new PdfReader(resource);
        PdfStamper stamper = new PdfStamper(pdfReader, output);
        
        TextField txtField = new TextField(stamper.getWriter(), newRect, newFldName);
        txtField.setTextColor(BaseColor.BLACK);
        txtField.setBackgroundColor(BaseColor.WHITE);
        txtField.setBorderColor(BaseColor.BLACK);
        txtField.setFieldName(newFldName);
        txtField.setAlignment(0); //LEFT
        txtField.setBorderStyle(0); //SOLID
        txtField.setBorderWidth(1.0F); //THIN
        txtField.setVisibility(TextField.VISIBLE);
        txtField.setRotation(0); //None
        txtField.setBox(newRect);
        //PdfArray opt = new PdfArray();
        List<String> ListBox_ItemDisplay = new ArrayList<String>();
        ListBox_ItemDisplay.add("One");
        ListBox_ItemDisplay.add("Two");
        ListBox_ItemDisplay.add("Three");
        ListBox_ItemDisplay.add("Four");
        ListBox_ItemDisplay.add("Five");
        List<String> ListBox_ItemValue = new ArrayList<String>();
        ListBox_ItemValue.add("1X");
        ListBox_ItemValue.add("2X");
        ListBox_ItemValue.add("3X");
        ListBox_ItemValue.add("4X");
        ListBox_ItemValue.add("5X");
        txtField.setOptions(txtField.getOptions() | TextField.MULTISELECT);
        ArrayList<Integer> selIndex = new ArrayList<Integer>();
        //List<String> selValues = new ArrayList<String>();
        selIndex.add(1); // SELECT #1 (index)
        selIndex.add(3); // SELECT #3 (index)
        txtField.setChoices(ListBox_ItemDisplay.toArray(new String[0]));
        txtField.setChoiceExports(ListBox_ItemValue.toArray(new String[0]));
        txtField.setChoiceSelections(selIndex);
        // vvv--- Add this line as a fix
        txtField.setVisibleTopChoice(0);
        // ^^^--- Add this line as a fix
        PdfFormField listField = txtField.getListField();
        stamper.addAnnotation(listField, pg);

        stamper.close();
    }
}
 
Example 17
Source File: InsertPage.java    From testarea-itext5 with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/28911509/how-to-retain-page-labels-when-concatenating-an-existing-pdf-with-a-pdf-created">
 * How to retain page labels when concatenating an existing pdf with a pdf created from scratch?
 * </a>
 * <p>
 * A proposal how to implement the task using a {@link PdfStamper}.
 */
@Test
public void testInsertTitlePage() throws IOException, DocumentException
{
    try (   InputStream documentStream = getClass().getResourceAsStream("Labels.pdf");
            InputStream titleStream = getClass().getResourceAsStream("Cover.pdf");
            OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "labels-with-cover-page.pdf"))    )
    {
        PdfReader titleReader = new PdfReader(titleStream);
        PdfReader reader = new PdfReader(documentStream);
        PdfStamper stamper = new PdfStamper(reader, outputStream);

        PdfImportedPage page = stamper.getImportedPage(titleReader, 1);
        stamper.insertPage(1, titleReader.getPageSize(1));
        PdfContentByte content = stamper.getUnderContent(1);
        content.addTemplate(page, 0, 0);
        copyLinks(stamper, 1, titleReader, 1);

        PdfDictionary root = reader.getCatalog();
        PdfDictionary labels = root.getAsDict(PdfName.PAGELABELS);
        if (labels != null)
        {
            PdfArray newNums = new PdfArray();
            
            newNums.add(new PdfNumber(0));
            PdfDictionary coverDict = new PdfDictionary();
            coverDict.put(PdfName.P, new PdfString("Cover Page"));
            newNums.add(coverDict);

            PdfArray nums = labels.getAsArray(PdfName.NUMS);
            if (nums != null)
            {
                for (int i = 0; i < nums.size() - 1; )
                {
                    int n = nums.getAsNumber(i++).intValue();
                    newNums.add(new PdfNumber(n+1));
                    newNums.add(nums.getPdfObject(i++));
                }
            }

            labels.put(PdfName.NUMS, newNums);
            stamper.markUsed(labels);
        }

        stamper.close();
    }
}
 
Example 18
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/38605538/itextpdf-redaction-partly-redacted-text-string-is-fully-removed">
 * itextpdf Redaction :Partly redacted text string is fully removed
 * </a>
 * <br/>
 * <a href="https://drive.google.com/file/d/0B42NqA5UnXMVMDc4MnE5VmU5YVk/view">
 * Document.pdf
 * </a>
 * <p>
 * This test applies the redaction using the {@link StrictPdfCleanUpProcessor}
 * which in contrast to the {@link PdfCleanUpProcessor} causes only text to be
 * removed if it is <b>completely</b> inside the redaction zone . The original
 * removes also text located merely <b>partially</b> inside the redaction zone.
 * Furthermore this test uses a larger redaction zone to check whether text
 * completely contained in the redaction zone really is removed.
 * </p>
 * <p>
 * This might more correspond to what the OP desires.
 * </p>
 * @see #testRedactLikeMayankPandey()
 * @see #testRedactStrictForMayankPandey()
 */
@Test
public void testRedactStrictForMayankPandeyLarge() throws IOException, DocumentException
{
    try (   InputStream resource = getClass().getResourceAsStream("Document.pdf");
            OutputStream result = new FileOutputStream(new File(OUTPUTDIR, "Document-redacted-strict-large.pdf")) )
    {
        PdfReader reader = new PdfReader(resource);
        StrictPdfCleanUpProcessor cleaner= null;
        PdfStamper stamper = new PdfStamper(reader, result);
        stamper.setRotateContents(false);
        List<mkl.testarea.itext5.pdfcleanup.PdfCleanUpLocation> cleanUpLocations = new ArrayList<>();
        Rectangle rectangle = new Rectangle(380, 640, 430, 680);
        cleanUpLocations.add(new mkl.testarea.itext5.pdfcleanup.PdfCleanUpLocation(1, rectangle, BaseColor.BLACK));
        cleaner = new StrictPdfCleanUpProcessor(cleanUpLocations, stamper);   
        cleaner.cleanUp();
        stamper.close();
        reader.close();
    }
}
 
Example 19
Source File: Stamping.java    From testarea-itext5 with GNU Affero General Public License v3.0 3 votes vote down vote up
/**
 * <a href = "http://stackoverflow.com/questions/28898636/itextpdf-stop-transform-pdf-correctly">
 * Itextpdf stop transform pdf correctly
 * </a>
 * <p>
 * <a href="https://drive.google.com/file/d/0B3-DPMN-iMOmNjItRVJ4MHRZX3M/view?usp=sharing">
 * template.pdf
 * </a>
 * <p>
 * ... as it turned out, the problem was not an iText issue at all; in the OP's web application
 * the template.pdf had already been mangled by maven resource filtering.
 * </p>
 */
@Test
public void testStampTemplate() throws DocumentException, IOException
{
    try (   InputStream resourceStream = getClass().getResourceAsStream("template.pdf");
            OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "test.pdf"))    )
    {
        PdfReader reader = new PdfReader(resourceStream);
        PdfStamper stamper = new PdfStamper(reader, outputStream);

        stamper.close();
    }
}
 
Example 20
Source File: BasicTemplating.java    From testarea-itext5 with GNU Affero General Public License v3.0 3 votes vote down vote up
/**
 * <p>
 * This test spawns a new page from a signed PDF; the template page had
 * been named before signing.
 * </p>
 * <p>
 * Unfortunately Adobe Acrobat Reader considers signatures broken after
 * page templates have been spawned unless the page template form xobject
 * has the same size after compression (!!) as if compressed by the Reader
 * itself. As different implementations of the deflate compression result
 * in different stream sizes, this makes it difficult to use this feature.
 * Furthermore, I don't see this size test backed by the PDF specification.
 * </p>
 * <p>
 * In case of the file "pdfa-named-signed-spawned.pdf" created by this test,
 * the length of the stream object 82 needs to be patched to 162 from the
 * 159 generated by iText.
 * </p>
 */
@Test
public void testSpawnPdfaNamedSigned() throws IOException, DocumentException
{
    try (   InputStream resource = getClass().getResourceAsStream("pdfa-named-signed.pdf");
            OutputStream target = new FileOutputStream(new File(RESULT_FOLDER, "pdfa-named-signed-spawned.pdf")) )
    {
        PdfReader pdfReader = new PdfReader(resource);
        PdfStamper pdfStamper = new PdfStamper(pdfReader, target, '\0', true);
        PdfStamperHelper.spawnTemplate(pdfStamper, "myTemplate0", 3);
        pdfStamper.close();
    }
}