Java Code Examples for org.apache.pdfbox.exceptions.COSVisitorException

The following are top voted examples for showing how to use org.apache.pdfbox.exceptions.COSVisitorException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: pdfboxExamples   File: PdfTable.java   Source Code and License 7 votes vote down vote up
@Test
public void test() throws IOException, COSVisitorException {

	PDDocument doc = new PDDocument();
	PDPage page = new PDPage();
	doc.addPage(page);
	PDPageContentStream contentStream = new PDPageContentStream(doc, page);

	String[][] content = { { "Team", "Captain" },
			{ "Hull City", "Robert Koren" },
			{ "Aston Villa", "Ron Vlaar" },
			{ "Manchester United", "Nemanja Vidic" },
			{ "Manchester City", "Vincent Kompany" } };

	drawTable(page, contentStream, 700, 100, content);

	contentStream.close();
	Path outputFilePath = Files.createTempFile("Test-CaptainTeam-Table", ".pdf");
	doc.save(outputFilePath.toFile());
	logger.info("test# "+ outputFilePath.toAbsolutePath().toString());

}
 
Example 2
Project: testarea-pdfbox1   File: RolloverAnnotation.java   Source Code and License 7 votes vote down vote up
void createRollover(PDAnnotation annotation, String filename) throws IOException, COSVisitorException
{
    PDDocument document = new PDDocument();
    PDPage page = new PDPage();
    document.addPage(page);
    List<PDAnnotation> annotations = page.getAnnotations();

    float x = 100;
    float y = 500;
    String text = "PDFBox";
    PDFont font = PDType1Font.HELVETICA_BOLD;
    float textWidth = font.getStringWidth(text) / 1000 * 18;

    PDPageContentStream contents = new PDPageContentStream(document, page);
    contents.beginText();
    contents.setFont(font, 18);
    contents.moveTextPositionByAmount(x, y);
    contents.drawString(text);
    contents.endText();
    contents.close();

    PDAppearanceDictionary appearanceDictionary = new PDAppearanceDictionary();
    PDAppearanceStream normal = createAppearanceStream(document, textWidth, font, "0.5 0.5 0.5 rg");
    PDAppearanceStream rollover = createAppearanceStream(document, textWidth, font, "1 0.7 0.5 rg");
    PDAppearanceStream down = createAppearanceStream(document, textWidth, font, "0 0 0 rg");
    appearanceDictionary.setNormalAppearance(normal);
    appearanceDictionary.setRolloverAppearance(rollover);
    appearanceDictionary.setDownAppearance(down);
    annotation.setAppearance(appearanceDictionary);

    PDRectangle position = new PDRectangle();
    position.setLowerLeftX(x);
    position.setLowerLeftY(y - 5);
    position.setUpperRightX(x + textWidth);
    position.setUpperRightY(y + 20);
    annotation.setRectangle(position);

    annotations.add(annotation);
    document.save(new File(RESULT_FOLDER, filename));
    document.close();
}
 
Example 3
Project: testarea-pdfbox1   File: ExtractWithoutExtraSpaces.java   Source Code and License 7 votes vote down vote up
byte[] createTestDocument() throws IOException, COSVisitorException
{
    try (   ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PDDocument doc = new PDDocument()   )
    {
        PDPage page = new PDPage(new PDRectangle(792, 612));
        doc.addPage(page);
        
        PDFont font = PDType1Font.COURIER;

        PDPageContentStream contents = new PDPageContentStream(doc, page);
        contents.beginText();
        contents.setFont(font, 9);
        contents.moveTextPositionByAmount(100, 500);
        contents.drawString("             2                                                                  Netto        5,00 EUR 3,00");
        contents.moveTextPositionByAmount(0, 0);
        contents.drawString("                2882892  ENERGIZE LR6 Industrial                     2,50 EUR 1");
        contents.endText();
        contents.close();
        
        doc.save(baos);
        
        return baos.toByteArray();
    }
}
 
Example 4
Project: PDFGal   File: PDFGalImpl.java   Source Code and License 7 votes vote down vote up
@Override
public void merge(final List<String> inputUris, final String outputUri)
		throws COSVisitorException, IOException {

	if (CollectionUtils.isNotEmpty(inputUris) && StringUtils.isNotBlank(outputUri)) {

		final PDFMergerUtility merger = new PDFMergerUtility();

		for (final String input : inputUris) {
			merger.addSource(input);
		}

		merger.setDestinationFileName(outputUri);
		merger.mergeDocuments();

	} else {
		throw new IllegalArgumentException(Constants.ILLEGAL_ARGUMENT_EXCEPTION_MESSAGE);
	}
}
 
Example 5
Project: OKKoPa   File: PDFSplitter.java   Source Code and License 7 votes vote down vote up
/**
 * Splits a PDF-document into exam papers.
 *
 * @param pdfStream PDF-file as InputStream
 * @return A List of ExamPapers.
 * @throws IOException If InputStream can not be read or stream doesn't
 * contain a PDF-format file.
 * @throws DocumentException If document contains odd number of pages.
 * @throws PdfException If a document is not in the right format or error
 * occurs while loading or splitting or document has an odd number of pages.
 * @throws COSVisitorException if something goes wrong when visiting a PDF
 * object.
 */
public List<ExamPaper> splitToExamPapersWithPDFStreams(InputStream pdfStream) throws IOException, DocumentException, PdfException, COSVisitorException {
    PDDocument allPdfDocument = PDDocument.load(pdfStream);
    if (allPdfDocument.getNumberOfPages() % 2 != 0) {
        throw new DocumentException("Odd number of pages");
    }
    Splitter splitter = new Splitter();
    splitter.setSplitAtPage(2);
    List<PDDocument> pdfDocuments = splitter.split(allPdfDocument);
    ArrayList<ExamPaper> examPapers = new ArrayList<>();
    for (PDDocument pdfDocument : pdfDocuments) {
        ExamPaper paper = new ExamPaper();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        pdfDocument.save(out);
        byte[] data = out.toByteArray();
        paper.setPdf(data);
        examPapers.add(paper);
        pdfDocument.close();
    }
    allPdfDocument.close();
    return examPapers;
}
 
Example 6
Project: pdfjumbler   File: PdfEditor.java   Source Code and License 6 votes vote down vote up
@Override
public void saveDocument(List<Page> pages, File file) throws IOException {
	if (pages.size() == 0) {
		throw new IOException("Empty document.");
	}
	
	PDDocument outDoc = new PDDocument();
	
	Map<File,PDDocument> docs = new HashMap<File,PDDocument>();
	try {
		for (Page page : pages) {
			PDDocument pageDoc = docs.get(page.getFile());
			if (pageDoc == null) {
				pageDoc = PDDocument.load(page.getFile());
				docs.put(page.getFile(), pageDoc);
			}
			
			outDoc.addPage((PDPage)pageDoc.getPrintable(page.getIndex()));
		}
		
		try {
			outDoc.save(file.toString());
		}
		catch (COSVisitorException e) {
			throw new IOException(e);
		}
	}
	finally {
		outDoc.close();
		for (PDDocument doc : docs.values()) {
			doc.close();
		}
	}
}
 
Example 7
Project: FBAPacklistPrinter   File: LabelTest.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws IOException, COSVisitorException {
String filename = args[0];
File f = new File(filename);
String outname = f.getName() + ".pdf";
Optional<Packlist> packlist = Packlist.from(new FileInputStream(f));
if (packlist.isPresent()) {
	//Initialize Document
       PDDocument doc = new PDDocument();	           
       ZebraTable table = createTable(doc, packlist.get());
       table.draw();
	
       //Close Stream and save pdf
       File file = new File(outname);
       System.out.println("Sample file saved at : " + file.getAbsolutePath());
       Files.createParentDirs(file);
       doc.save(file);
       doc.close();
}
  }
 
Example 8
Project: testarea-pdfbox1   File: CreateSignature.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws IOException, GeneralSecurityException, SignatureException, COSVisitorException {
    char[] password = "123456".toCharArray();

    KeyStore keystore = KeyStore.getInstance("PKCS12");
    keystore.load(new FileInputStream("/home/user/Desktop/keystore.p12"), password);

    Enumeration<String> aliases = keystore.aliases();
    String alias;
    if (aliases.hasMoreElements()) {
        alias = aliases.nextElement();
    } else {
        throw new KeyStoreException("Keystore is empty");
    }
    privateKey = (PrivateKey) keystore.getKey(alias, password);
    Certificate[] certificateChain = keystore.getCertificateChain(alias);
    certificate = certificateChain[0];

    File inFile = new File("/home/user/Desktop/sign.pdf");
    File outFile = new File("/home/user/Desktop/sign_signed.pdf");
    new CreateSignature().signPdf(inFile, outFile);
}
 
Example 9
Project: testarea-pdfbox1   File: OverlayWithEffect.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws COSVisitorException, IOException
{
    InputStream sourceStream = new FileInputStream("src/test/resources/mkl/testarea/pdfbox1/assembly/pdf-test.pdf");
    InputStream overlayStream = new FileInputStream("src/test/resources/mkl/testarea/pdfbox1/assembly/draft1.pdf");
    try {
        final PDDocument document = PDDocument.load(sourceStream);
        final PDDocument overlay = PDDocument.load(overlayStream);

        overlayWithDarkenBlendMode(document, overlay);

        document.save(new File(RESULT_FOLDER, "da-draft-5.pdf").toString());
        document.close();
    }
    finally {
        sourceStream.close();
        overlayStream.close();
    }
}
 
Example 10
Project: testarea-pdfbox1   File: SignLikePdfboxExample.java   Source Code and License 6 votes vote down vote up
void createVisibleSignature(File document, File ksFile, char[] pin, InputStream image, String signatureFieldName) throws IOException, COSVisitorException, SignatureException, GeneralSecurityException
{
    KeyStore keystore = KeyStore.getInstance("PKCS12", provider);
    keystore.load(new FileInputStream(ksFile), pin);

    CreateVisibleSignature signing = new CreateVisibleSignature(keystore, pin.clone());

    PDVisibleSignDesigner visibleSig = new PDVisibleSignDesigner(document.getAbsolutePath(), image, 1);
    visibleSig.xAxis(0).yAxis(0).zoom(-50).signatureFieldName(signatureFieldName);

    PDVisibleSigProperties signatureProperties = new PDVisibleSigProperties();

    signatureProperties.signerName("name").signerLocation("location").signatureReason("Security").preferredSize(0)
        .page(1).visualSignEnabled(true).setPdVisibleSignature(visibleSig).buildSignature();

    signing.signPDF(document, signatureProperties);
}
 
Example 11
Project: testarea-pdfbox1   File: SignLikeDenisMP.java   Source Code and License 6 votes vote down vote up
@Test
public void testOriginalA() throws IOException, COSVisitorException, SignatureException
{
    CreateVisibleSignature signing = new CreateVisibleSignature(
            keystore, password.clone());
    InputStream image = getClass().getResourceAsStream("Willi-1.jpg");
    PDVisibleSignDesigner visibleSig = new PDVisibleSignDesigner(
            document.toString(), image, 1);
    visibleSig.xAxis(0).yAxis(0).zoom(-75)
            .signatureFieldName("ApplicantSignature"); // ("topmostSubform[0].Page3[0].SignatureField1[0]")
    PDVisibleSigProperties signatureProperties = new PDVisibleSigProperties();
    signatureProperties.signerName("name").signerLocation("location")
            .signatureReason("Security").preferredSize(0).page(3)
            .visualSignEnabled(true).setPdVisibleSignature(visibleSig)
            .buildSignature();
    signing.signPDF(document, signatureProperties);
}
 
Example 12
Project: testarea-pdfbox1   File: SignInMemory.java   Source Code and License 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/29123436/how-to-sign-an-inputstream-from-a-pdf-file-with-pdfbox-2-0-0">
 * How to sign an InputStream from a PDF file with PDFBox 2.0.0
 * </a>
 * 
 * Test the equivalent for PDFBox 1.8.8. Works alright.
 */
@Test
public void testDummySignInMemory() throws IOException, COSVisitorException, SignatureException
{
    try (   InputStream sourceStream = getClass().getResourceAsStream("/mkl/testarea/pdfbox1/assembly/document1.pdf");
            OutputStream output = new FileOutputStream(new File(RESULT_FOLDER, "document1-with-dummy-sig.pdf")))
    {
        byte[] input = IOUtils.toByteArray(sourceStream);
        output.write(input);
        signDetached(input, output, new SignatureInterface()
                {
                    @Override
                    public byte[] sign(InputStream content) throws SignatureException, IOException
                    {
                        return "Test".getBytes();
                    }
                });
    }
}
 
Example 13
Project: testarea-pdfbox1   File: SignInMemory.java   Source Code and License 6 votes vote down vote up
void signDetached(byte[] pdf, OutputStream output, SignatureInterface signatureInterface)throws IOException, SignatureException, COSVisitorException
{
    PDDocument document = PDDocument.load(new ByteArrayInputStream(pdf));
    // create signature dictionary
    PDSignature signature = new PDSignature();
    signature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE);
    signature.setSubFilter(PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED);
    signature.setName("Example User");
    signature.setLocation("Los Angeles, CA");
    signature.setReason("Testing");
    // TODO extract the above details from the signing certificate? Reason as a parameter?

    // the signing date, needed for valid signature
    signature.setSignDate(Calendar.getInstance());

    // register signature dictionary and sign interface
    document.addSignature(signature, signatureInterface);

    // write incremental (only for signing purpose)
    document.saveIncremental(new ByteArrayInputStream(pdf), output);
}
 
Example 14
Project: testarea-pdfbox1   File: AddValidationRelatedInformation.java   Source Code and License 6 votes vote down vote up
void test(String resourceName, File resultFile) throws IOException, COSVisitorException, CertificateEncodingException
{
    try (   InputStream source = getClass().getResourceAsStream(resourceName);
            FileOutputStream fos = new FileOutputStream(resultFile);
            FileInputStream fis = new FileInputStream(resultFile);
            )
    {
        List<byte[]> certificates = new ArrayList<byte[]>();
        for (int i = 0; i < cert.length; i++)
            certificates.add(cert[i].getEncoded());
        COSDictionary dss = createDssDictionary(certificates, null, null);

        byte inputBytes[] = IOUtils.toByteArray(source);

        PDDocument pdDocument = PDDocument.load(new ByteArrayInputStream(inputBytes));
        PDDocumentCatalog catalog = pdDocument.getDocumentCatalog();
        catalog.getCOSObject().setNeedToBeUpdate(true);
        catalog.getCOSDictionary().setItem(COSName.getPDFName("DSS"), dss);

        fos.write(inputBytes);
        pdDocument.saveIncremental(fis, fos);
        pdDocument.close();
    }
}
 
Example 15
Project: testarea-pdfbox1   File: OverwriteImage.java   Source Code and License 6 votes vote down vote up
/**
 * Applying the code to the OP's sample file from a former question.
 * 
 * @throws IOException
 * @throws CryptographyException
 * @throws COSVisitorException
 */
@Test
public void testDrunkenFistSample() throws IOException, CryptographyException, COSVisitorException
{
    try (   InputStream resource = getClass().getResourceAsStream("sample.pdf");
            InputStream left = getClass().getResourceAsStream("left.png");
            InputStream right = getClass().getResourceAsStream("right.png");
            PDDocument document = PDDocument.load(resource) )
    {
        if (document.isEncrypted())
        {
            document.decrypt("");
        }
        
        PDJpeg leftImage = new PDJpeg(document, ImageIO.read(left));
        PDJpeg rightImage = new PDJpeg(document, ImageIO.read(right));

        ImageLocator locator = new ImageLocator();
        List<?> allPages = document.getDocumentCatalog().getAllPages();
        for (int i = 0; i < allPages.size(); i++)
        {
            PDPage page = (PDPage) allPages.get(i);
            locator.processStream(page, page.findResources(), page.getContents().getStream());
        }

        for (ImageLocation location : locator.getLocations())
        {
            PDRectangle cropBox = location.getPage().findCropBox();
            float center = (cropBox.getLowerLeftX() + cropBox.getUpperRightX()) / 2.0f;
            PDJpeg image = location.getMatrix().getXPosition() < center ? leftImage : rightImage;
            AffineTransform transform = location.getMatrix().createAffineTransform();

            PDPageContentStream content = new PDPageContentStream(document, location.getPage(), true, false, true);
            content.drawXObject(image, transform);
            content.close();
        }

        document.save(new File(RESULT_FOLDER, "sample-changed.pdf"));
    }
}
 
Example 16
Project: testarea-pdfbox1   File: DrawSpecialCharacters.java   Source Code and License 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/22260344/pdfbox-encode-symbol-currency-euro">
 * PdfBox encode symbol currency euro
 * </a>
 * <p>
 * Three ways of trying to draw a '�' symbol, the first one fails.
 * </p>
 */
@Test
public void testDrawEuro() throws IOException, COSVisitorException
{
    PDDocument document = new PDDocument();
    PDPage page = new PDPage();
    document.addPage(page);
    PDPageContentStream contents = new PDPageContentStream(document, page);
    PDFont font = PDType1Font.HELVETICA_BOLD;
    contents.beginText();
    contents.setFont(font, 18);
    contents.moveTextPositionByAmount(30, 600);
    contents.drawString("�");
    contents.moveTextPositionByAmount(0, -30);
    contents.drawString(String.valueOf(Character.toChars(EncodingManager.INSTANCE.getEncoding(COSName.WIN_ANSI_ENCODING).getCode("Euro"))));
    contents.moveTextPositionByAmount(0, -30);
    byte[] commands = "(x) Tj ".getBytes();
    commands[1] = (byte) 128;
    contents.appendRawCommands(commands);
    contents.endText();
    contents.close();
    document.save(new File(RESULT_FOLDER, "Euro.pdf"));
    document.close();
}
 
Example 17
Project: testarea-pdfbox1   File: DrawSpecialCharacters.java   Source Code and License 6 votes vote down vote up
/**
    * <a href="http://stackoverflow.com/questions/30619974/pdfbox-unable-to-write-superscripted-characters">
    * PDFBox unable to write superscripted characters
    * </a>
    * <p>
    * {@link #testDrawTmSignBroken()} represents the observation the OP made,
    * {@link #testDrawTmSignCustomDraw()} is a solution using custom drawing operations, and
    * {@link #testDrawTmSignLetters()} is a solution drawing the trademark symbol using smaller letters with text rise.
    * </p>
    */
@Test
public void testDrawTmSignBroken() throws IOException, COSVisitorException
{
	PDDocument document = new PDDocument();
       PDPage page = new PDPage();
       document.addPage(page);
       PDPageContentStream contents = new PDPageContentStream(document, page);
       PDFont font = PDType1Font.HELVETICA_BOLD;
       contents.beginText();
       contents.setFont(font, 18);
       contents.moveTextPositionByAmount(30, 600);
       contents.drawString("90000039-PREDISOL � C YELLOW 13 SNDOT�M");
       contents.endText();
       contents.close();
       document.save(new File(RESULT_FOLDER, "TM_naive.pdf"));
       document.close();
}
 
Example 18
Project: testarea-pdfbox1   File: DrawSpecialCharacters.java   Source Code and License 6 votes vote down vote up
@Test
public void testDrawTmSignCustomDraw() throws IOException, COSVisitorException
{
	PDDocument document = new PDDocument();
       PDPage page = new PDPage();
       document.addPage(page);
       PDPageContentStream contents = new PDPageContentStream(document, page);
       PDFont font = PDType1Font.HELVETICA_BOLD;
       contents.beginText();
       contents.setFont(font, 18);
       contents.moveTextPositionByAmount(30, 600);
       contents.drawString("90000039-PREDISOL � C YELLOW 13 SNDOT");
       byte[] commands = "(x) Tj ".getBytes();
       commands[1] = (byte) 0231;
       contents.appendRawCommands(commands);
       contents.drawString("M");
       contents.endText();
       contents.close();
       document.save(new File(RESULT_FOLDER, "TM_customDraw.pdf"));
       document.close();
}
 
Example 19
Project: testarea-pdfbox1   File: DrawSpecialCharacters.java   Source Code and License 6 votes vote down vote up
@Test
public void testDrawTmSignLetters() throws IOException, COSVisitorException
{
	PDDocument document = new PDDocument();
       PDPage page = new PDPage();
       document.addPage(page);
       PDPageContentStream contents = new PDPageContentStream(document, page);
       PDFont font = PDType1Font.HELVETICA_BOLD;
       contents.beginText();
       contents.setFont(font, 18);
       contents.moveTextPositionByAmount(30, 600);
       contents.drawString("90000039-PREDISOL � C YELLOW 13 SNDOT");
       contents.appendRawCommands("\n6 Ts\n".getBytes());
       contents.setFont(font, 10);
       contents.drawString("TM");
       contents.appendRawCommands("\n0 Ts\n".getBytes());
       contents.setFont(font, 18);
       contents.drawString("M");
       contents.endText();
       contents.close();
       document.save(new File(RESULT_FOLDER, "TM_letters.pdf"));
       document.close();
}
 
Example 20
Project: testarea-pdfbox1   File: UnderlayText.java   Source Code and License 6 votes vote down vote up
/**
 * Execute the test for sample.pdf. The results are as expected even
 * though one misses the watermark after pushing under; as there is a
 * big white rectangle drawn first in the pre-existing content, though,
 * this is correct, the watermark is hidden under that rectangle.
 */
@Test
public void testSample() throws IOException, COSVisitorException
{
    try (   InputStream resourceStream = getClass().getResourceAsStream("sample.pdf")   )
    {
        PDDocument document = PDDocument.loadNonSeq(resourceStream, null);
        PDFont pdfFont = PDFontFactory.createDefaultFont();

        watermarkOriginal(document, pdfFont, 45, 400, 550, "Test");
        document.save(new File(RESULT_FOLDER, "sample-underlayOriginal.pdf"));
        
        pushUnder(document);
        document.save(new File(RESULT_FOLDER, "sample-underlayPushedUnder.pdf"));

        document.close();
    }
}
 
Example 21
Project: testarea-pdfbox1   File: UnderlayText.java   Source Code and License 6 votes vote down vote up
/**
 * Execute the test for testA4.pdf. The results are as expected
 */
@Test
public void testTestA4() throws IOException, COSVisitorException
{
    try (   InputStream resourceStream = getClass().getResourceAsStream("testA4.pdf")   )
    {
        PDDocument document = PDDocument.loadNonSeq(resourceStream, null);
        PDFont pdfFont = PDFontFactory.createDefaultFont();

        watermarkOriginal(document, pdfFont, 45, 200, 600, "Test");
        document.save(new File(RESULT_FOLDER, "testA4-underlayOriginal.pdf"));
        
        pushUnder(document);
        document.save(new File(RESULT_FOLDER, "testA4-underlayPushedUnder.pdf"));

        document.close();
    }
}
 
Example 22
Project: testarea-pdfbox1   File: AddContentToOCG.java   Source Code and License 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/43275212/how-do-i-make-modifications-to-existing-layeroptional-content-group-in-pdf">
 * How do I make modifications to existing layer(Optional Content Group) in pdf?
 * </a>
 * <p>
 * This test show how add content to an optional content group which
 * may or may not already exist.
 * </p>
 * @see #addTextToLayer(PDDocument, int, String, float, float, String)
 */
@Test
public void testAddContentToNewOrExistingOCG() throws COSVisitorException, IOException
{
    PDDocument document = new PDDocument();
    PDPage page = new PDPage();
    document.addPage(page);

    addTextToLayer(document, 0, "MyLayer", 30, 600, "Text in new layer 'MyLayer'");
    addTextToLayer(document, 0, "MyOtherLayer", 230, 550, "Text in new layer 'MyOtherLayer'");
    addTextToLayer(document, 0, "MyLayer", 30, 500, "Text in existing layer 'MyLayer'");
    addTextToLayer(document, 0, "MyOtherLayer", 230, 450, "Text in existing layer 'MyOtherLayer'");

    document.save(new File(RESULT_FOLDER, "TextInOCGs.pdf"));
    document.close();
}
 
Example 23
Project: testarea-pdfbox1   File: InsertPages.java   Source Code and License 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/35964628/pdfbox-split-into-3-at-specified-page-numbers-to-insert-pdf">
 * PDFBox Split into 3 at specified page numbers (to insert pdf)
 * </a>
 * <p>
 * This test shows how to insert the same single page into another document multiple times.
 * </p>
 * <p>
 * Beware, this code assumes a flat page tree. In case of deeper page trees one has to
 * walk the page list differently, respect the count of contained {@link PDPageNode}
 * objects and recurse if appropriate. 
 * </p>
 */
@Test
public void testInsertPages() throws IOException, COSVisitorException
{
    PDDocument document = create100Pages();
    PDDocument singlePageDocument = create1Page("A");
    PDPage singlePage = (PDPage) singlePageDocument.getDocumentCatalog().getAllPages().get(0);
    
    PDPageNode rootPages = document.getDocumentCatalog().getPages();
    rootPages.getKids().add(3-1, singlePage);
    singlePage.setParent(rootPages);
    singlePage = new PDPage(new COSDictionary(singlePage.getCOSDictionary()));
    rootPages.getKids().add(7-1, singlePage);
    singlePage = new PDPage(new COSDictionary(singlePage.getCOSDictionary()));
    rootPages.getKids().add(10-1, singlePage);
    rootPages.updateCount();
    
    document.save(new File(RESULT_FOLDER, "100-A-at-3.pdf"));
}
 
Example 24
Project: testarea-pdfbox1   File: ExtractText.java   Source Code and License 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/37566288/pdfbox-is-not-giving-right-output">
 * PDFBOX is not giving right output
 * </a>
 * <br/>
 * <a href="https://www.dropbox.com/s/bsm4zgv5v0mvj7v/Airtel.pdf?dl=0">
 * Airtel.pdf
 * </a>
 * <p>
 * Indeed, PDFBox text extraction hardly returns anything. But inspecting the PDF in question
 * makes clear why it is so: Virtually all "text" in the document is not drawn using text
 * drawing instructions but instead by defining the character outlines as paths and filling
 * them. Thus, hardly anything short of OCR will help here.
 * </p>
 */
@Test
public void testExtractAsMudit() throws COSVisitorException, IOException
{
    try (   InputStream documentStream = getClass().getResourceAsStream("Airtel.pdf");
            PDDocument document = PDDocument.load(documentStream))
    {
        PDFTextStripper pdfStripper = new PDFTextStripper();
        pdfStripper.setStartPage(1);
        pdfStripper.setEndPage(1);
        String parsedText = pdfStripper.getText(document);

        System.out.println("\n'Airtel.pdf', extract as Mudit:");
        System.out.println(parsedText);
        System.out.println("***********************************");
    }
}
 
Example 25
Project: testarea-pdfbox1   File: ExtractWithoutExtraSpaces.java   Source Code and License 6 votes vote down vote up
@Test
public void testExtractFromTestDocument() throws COSVisitorException, IOException
{
    byte[] documentBytes = createTestDocument();
    Files.write(new File(RESULT_FOLDER, "TestDocument.pdf").toPath(), documentBytes);

    try (   InputStream documentStream = new ByteArrayInputStream(documentBytes);
            PDDocument document = PDDocument.load(documentStream))
    {
        String normal = extractNormal(document);
        String noSpaces = extractNoSpaces(document);

        System.out.println("\nTestDocument, extract normally:");
        System.out.println("> " + normal);
        System.out.println("\nTestDocument, extract no-spaces:");
        System.out.println("> " + noSpaces);
    }
}
 
Example 26
Project: PDFGal   File: PDFGalImpl.java   Source Code and License 6 votes vote down vote up
@Override
public void protect(final String inputUri, final String outputUri, final String password)
		throws IOException, BadSecurityHandlerException, COSVisitorException {

	if (StringUtils.isNotBlank(inputUri) && StringUtils.isNotBlank(outputUri)
			&& StringUtils.isNotBlank(password)) {

		final PDDocument doc = PDDocument.load(inputUri);

		final StandardProtectionPolicy pp = new StandardProtectionPolicy(password, password,
				new AccessPermission());
		doc.protect(pp);

		doc.save(outputUri);

		doc.close();

	} else {
		throw new IllegalArgumentException(Constants.ILLEGAL_ARGUMENT_EXCEPTION_MESSAGE);
	}
}
 
Example 27
Project: PDFGal   File: PDFGalImpl.java   Source Code and License 6 votes vote down vote up
@Override
public void unProtect(final String inputUri, final String outputUri, final String password)
		throws IOException, COSVisitorException, BadSecurityHandlerException,
		CryptographyException {

	if (StringUtils.isNotBlank(inputUri) && StringUtils.isNotBlank(outputUri)
			&& StringUtils.isNotBlank(password)) {

		final PDDocument doc = PDDocument.load(inputUri);

		final DecryptionMaterial decryptionMaterial = new StandardDecryptionMaterial(password);
		doc.openProtection(decryptionMaterial);

		final StandardProtectionPolicy pp = new StandardProtectionPolicy(null, null,
				new AccessPermission());
		doc.protect(pp);

		doc.save(outputUri);

		doc.close();

	} else {
		throw new IllegalArgumentException(Constants.ILLEGAL_ARGUMENT_EXCEPTION_MESSAGE);
	}
}
 
Example 28
Project: jabref   File: XMPUtilTest.java   Source Code and License 6 votes vote down vote up
/**
 * Write a manually constructed xmp-string to file
 *
 * @param xmpString
 * @throws IOException
 * @throws COSVisitorException
 */
public void writeManually(File tempFile, String xmpString) throws IOException, COSVisitorException {

    try (PDDocument document = PDDocument.load(tempFile.getAbsoluteFile())) {
        if (document.isEncrypted()) {
            Assert.fail("Cannot add metadata to encrypted document.");
        }

        PDDocumentCatalog catalog = document.getDocumentCatalog();

        // Convert to UTF8 and make available for metadata.
        ByteArrayOutputStream bs = new ByteArrayOutputStream();
        try (OutputStreamWriter os = new OutputStreamWriter(bs, StandardCharsets.UTF_8)) {
            os.write(xmpString);
        }
        ByteArrayInputStream in = new ByteArrayInputStream(bs.toByteArray());

        PDMetadata metadataStream = new PDMetadata(document, in, false);
        catalog.setMetadata(metadataStream);

        document.save(tempFile.getAbsolutePath());

    }
}
 
Example 29
Project: jabref   File: XMPUtilTest.java   Source Code and License 6 votes vote down vote up
/**
 * Create a temporary PDF-file with a single empty page.
 */
@Before
public void setUp() throws IOException, COSVisitorException {

    pdfFile = tempFolder.newFile("JabRef.pdf");

    try (PDDocument pdf = new PDDocument()) {
        //Need page to open in Acrobat
        pdf.addPage(new PDPage());
        pdf.save(pdfFile.getAbsolutePath());
    }

    importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS);
    when(importFormatPreferences.getEncoding()).thenReturn(StandardCharsets.UTF_8);
    xmpPreferences = mock(XMPPreferences.class);
    // The code assumes privacy filters to be off
    when(xmpPreferences.isUseXMPPrivacyFilter()).thenReturn(false);

    when(xmpPreferences.getKeywordSeparator()).thenReturn(',');
}
 
Example 30
Project: jabref   File: XMPUtilTest.java   Source Code and License 6 votes vote down vote up
/**
 * Most basic test for reading.
 * @throws IOException
 * @throws COSVisitorException
 */
@Test
public void testReadXMPSimple() throws COSVisitorException, IOException {

    String bibtex = "<bibtex:year>2003</bibtex:year>\n"
            + "<bibtex:title>Beach sand convolution by surf-wave optimzation</bibtex:title>\n"
            + "<bibtex:bibtexkey>OezbekC06</bibtex:bibtexkey>\n";

    writeManually(pdfFile, XMPUtilTest.bibtexXPacket(XMPUtilTest.bibtexDescription(bibtex)));

    List<BibEntry> l = XMPUtil.readXMP(pdfFile.getAbsoluteFile(), xmpPreferences);
    Assert.assertEquals(1, l.size());
    BibEntry e = l.get(0);

    Assert.assertNotNull(e);
    Assert.assertEquals(Optional.of("OezbekC06"), e.getCiteKeyOptional());
    Assert.assertEquals(Optional.of("2003"), e.getField("year"));
    Assert.assertEquals(Optional.of("Beach sand convolution by surf-wave optimzation"),
            e.getField("title"));
    Assert.assertEquals("misc", e.getType());
}
 
Example 31
Project: jabref   File: XMPUtilTest.java   Source Code and License 6 votes vote down vote up
/**
 * Is UTF8 handling working? This is because Java by default uses the platform encoding or a special UTF-kind.
 * @throws IOException
 * @throws COSVisitorException
 */
@Test
public void testReadXMPUTF8() throws COSVisitorException, IOException {

    String bibtex = "<bibtex:year>2003</bibtex:year>\n" + "<bibtex:title>�pt�mz�t��n</bibtex:title>\n"
            + "<bibtex:bibtexkey>OezbekC06</bibtex:bibtexkey>\n";

    writeManually(pdfFile, XMPUtilTest.bibtexXPacket(XMPUtilTest.bibtexDescription(bibtex)));

    List<BibEntry> l = XMPUtil.readXMP(pdfFile.getAbsoluteFile(), xmpPreferences);
    Assert.assertEquals(1, l.size());
    BibEntry e = l.get(0);

    Assert.assertNotNull(e);
    Assert.assertEquals(Optional.of("OezbekC06"), e.getCiteKeyOptional());
    Assert.assertEquals(Optional.of("2003"), e.getField("year"));
    Assert.assertEquals(Optional.of("�pt�mz�t��n"), e.getField("title"));
    Assert.assertEquals("misc", e.getType());
}
 
Example 32
Project: jabref   File: XMPUtilTest.java   Source Code and License 6 votes vote down vote up
/**
 * Are authors and editors correctly read?
 * @throws IOException
 * @throws COSVisitorException
 */
@Test
public void testReadXMPSeq() throws COSVisitorException, IOException {

    String bibtex = "<bibtex:author><rdf:Seq>\n" + "  <rdf:li>Kelly Clarkson</rdf:li>"
            + "  <rdf:li>Ozzy Osbourne</rdf:li>" + "</rdf:Seq></bibtex:author>" + "<bibtex:editor><rdf:Seq>"
            + "  <rdf:li>Huey Duck</rdf:li>" + "  <rdf:li>Dewey Duck</rdf:li>" + "  <rdf:li>Louie Duck</rdf:li>"
            + "</rdf:Seq></bibtex:editor>" + "<bibtex:bibtexkey>Clarkson06</bibtex:bibtexkey>";

    writeManually(pdfFile, XMPUtilTest.bibtexXPacket(XMPUtilTest.bibtexDescription(bibtex)));

    List<BibEntry> l = XMPUtil.readXMP(pdfFile.getAbsoluteFile(), xmpPreferences);
    Assert.assertEquals(1, l.size());
    BibEntry e = l.get(0);

    Assert.assertNotNull(e);
    Assert.assertEquals(Optional.of("Clarkson06"), e.getCiteKeyOptional());
    Assert.assertEquals("Kelly Clarkson and Ozzy Osbourne", e.getField("author").get());
    Assert.assertEquals("Huey Duck and Dewey Duck and Louie Duck", e.getField("editor").get());
    Assert.assertEquals("misc", e.getType());
}
 
Example 33
Project: jabref   File: XMPUtilTest.java   Source Code and License 6 votes vote down vote up
/**
 * Test whether the helper function work correctly.
 * @throws IOException
 * @throws COSVisitorException
 */
@Test
public void testWriteReadManually() throws COSVisitorException, IOException {

    String bibtex = "<bibtex:year>2003</bibtex:year>\n" + "<bibtex:title>�pt�mz�t��n</bibtex:title>\n"
            + "<bibtex:bibtexkey>OezbekC06</bibtex:bibtexkey>\n";

    writeManually(pdfFile, XMPUtilTest.bibtexXPacket(XMPUtilTest.bibtexDescription(bibtex)));
    Assert.assertEquals(XMPUtilTest.bibtexXPacket(XMPUtilTest.bibtexDescription(bibtex)),
            XMPUtilTest.readManually(pdfFile));

    bibtex = "<bibtex:author><rdf:Seq>\n" + "  <rdf:li>Kelly Clarkson</rdf:li>" + "  <rdf:li>Ozzy Osbourne</rdf:li>"
            + "</rdf:Seq></bibtex:author>" + "<bibtex:editor><rdf:Seq>" + "  <rdf:li>Huey Duck</rdf:li>"
            + "  <rdf:li>Dewey Duck</rdf:li>" + "  <rdf:li>Louie Duck</rdf:li>" + "</rdf:Seq></bibtex:editor>"
            + "<bibtex:bibtexkey>Clarkson06</bibtex:bibtexkey>";

    writeManually(pdfFile, XMPUtilTest.bibtexXPacket(XMPUtilTest.bibtexDescription(bibtex)));
    Assert.assertEquals(XMPUtilTest.bibtexXPacket(XMPUtilTest.bibtexDescription(bibtex)),
            XMPUtilTest.readManually(pdfFile));
}
 
Example 34
Project: jabref   File: XMPUtilTest.java   Source Code and License 6 votes vote down vote up
/**
 * Are newlines in the XML processed correctly?
 * @throws IOException
 * @throws COSVisitorException
 *
 */
@Test
public void testNewlineHandling() throws COSVisitorException, IOException {

    String bibtex = "<bibtex:title>\nHallo\nWorld \nthis \n is\n\nnot \n\nan \n\n exercise \n \n.\n \n\n</bibtex:title>\n"
            + "<bibtex:tabs>\nHallo\tWorld \tthis \t is\t\tnot \t\tan \t\n exercise \t \n.\t \n\t</bibtex:tabs>\n"
            + "<bibtex:abstract>\n\nAbstract preserve\n\t Whitespace\n\n</bibtex:abstract>";

    writeManually(pdfFile, XMPUtilTest.bibtexXPacket(XMPUtilTest.bibtexDescription(bibtex)));

    List<BibEntry> l = XMPUtil.readXMP(pdfFile.getAbsoluteFile(), xmpPreferences);
    Assert.assertEquals(1, l.size());
    BibEntry e = l.get(0);

    Assert.assertNotNull(e);
    Assert.assertEquals("Hallo World this is not an exercise .", e.getField("title").get());
    Assert.assertEquals("Hallo World this is not an exercise .", e.getField("tabs").get());
    Assert.assertEquals("\n\nAbstract preserve\n\t Whitespace\n\n", e.getField("abstract").get());
}
 
Example 35
Project: jabref   File: XMPUtilTest.java   Source Code and License 6 votes vote down vote up
/**
 * Test whether the command-line client works correctly with writing a single entry
 * @throws IOException
 * @throws TransformerException
 * @throws COSVisitorException
 *

 */
@Test
public void testCommandLineSingleBib() throws IOException, TransformerException, COSVisitorException {

    // First check conversion from .bib to .xmp
    File tempBib =  tempFolder.newFile("JabRef.bib");
    try (BufferedWriter fileWriter = Files.newBufferedWriter(tempBib.toPath(), StandardCharsets.UTF_8)) {
        fileWriter.write(t1BibtexString());
        fileWriter.close();

        try (ByteArrayOutputStream s = new ByteArrayOutputStream()) {
            PrintStream oldOut = System.out;
            System.setOut(new PrintStream(s));
            XMPUtilMain.main(new String[] {tempBib.getAbsolutePath()});
            System.setOut(oldOut);
            String xmp = s.toString();

            writeManually(pdfFile, xmp);
        }
        List<BibEntry> l = XMPUtil.readXMP(pdfFile, xmpPreferences);
        Assert.assertEquals(1, l.size());
        assertEqualsBibtexEntry(t1BibtexEntry(), l.get(0));

    }
}
 
Example 36
Project: cerfa-form-filler   File: Application.java   Source Code and License 6 votes vote down vote up
public static Result generateFake(String formId) throws IOException, COSVisitorException {
    Forms form = getForm(formId);
    if (null == form) {
        return badRequest(String.format("Formulaire inconnu : %s", formId));
    }

    FormFiller filler = createFormFiller(form);
    filler.fillFake();

    File file = File.createTempFile("tmp", ".pdf");
    try {
        filler.getWriter().save(file);

        return ok(file, formId.concat(".pdf"));
    } finally {
        file.delete();
    }
}
 
Example 37
Project: esup-dematec   File: TxPdfService.java   Source Code and License 6 votes vote down vote up
public void mergePdfs(List<InputStream> pdfFiles, String filename, OutputStream destStream) {
	PDFMergerUtility ut = new PDFMergerUtility();
	ut.setDestinationFileName(filename);
	ut.setDestinationStream(destStream);
	for(InputStream pdfFile: pdfFiles) {
		ut.addSource(pdfFile);
	}
	try {
		ut.mergeDocuments();
	} catch (COSVisitorException | IOException e) {
		throw new EsupDematEcException("Error merging pdf files- " + filename, e);
	}	
}
 
Example 38
Project: dainik-bhasker-pdf   File: Init.java   Source Code and License 6 votes vote down vote up
private static void mergeAllPages(final String directoryName) throws IOException,
        COSVisitorException {

    File[] files = new File(directoryName).listFiles();

    Arrays.sort(files, new Comparator<File>() {
        public int compare(File f1, File f2) {
            return Long.valueOf(f1.lastModified()).compareTo(
                    f2.lastModified());
        }
    });

    PDFMergerUtility ut = new PDFMergerUtility();
    for (File pdfFile : files) {
        ut.addSource(pdfFile);
    }

    ut.setDestinationFileName(directoryName + BACK_SLASH + "merged.pdf");
    logInfo("Starting merge at : " + directoryName + BACK_SLASH
            + "merged.pdf");
    ut.mergeDocuments();
    logInfo("Created merged pdf at : " + directoryName
            + BACK_SLASH + "merged.pdf");

}
 
Example 39
Project: arks-api   File: SplitDemo.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    // Load the PDF. The PDDocument throws IOException
    PDDocument document = new PDDocument();
    document = PDDocument.load("C:\\Main.pdf");
    
    // Create a Splitter object
    Splitter splitter = new Splitter();
    
    // We need this as split method returns a list
    List<PDDocument> listOfSplitPages;
    
    // We are receiving the split pages as a list of PDFs
    listOfSplitPages = splitter.split(document);
    
    // We need an iterator to iterate through them
    Iterator<PDDocument> iterator = listOfSplitPages.listIterator();
    
    // I am using variable i to denote page numbers. 
    int i = 1;
    while(iterator.hasNext()){
        PDDocument pd = iterator.next();
        try{
            // Saving each page with its assumed page no.
            pd.save("C:\\Page " + i++ + ".pdf");
        } catch (COSVisitorException anException){
            // Something went wrong with a PDF object
            System.out.println("Something went wrong with page " + (i-1) + "\n Here is the error message" + anException);                
        }            
    }        
}
 
Example 40
Project: Camel   File: PdfProducer.java   Source Code and License 5 votes vote down vote up
private Object doAppend(Exchange exchange) throws IOException, BadSecurityHandlerException, CryptographyException, InvalidPasswordException, COSVisitorException {
    LOG.debug("Got {} operation, going to append text to provided pdf.", pdfConfiguration.getOperation());
    String body = exchange.getIn().getBody(String.class);
    PDDocument document = exchange.getIn().getHeader(PDF_DOCUMENT_HEADER_NAME, PDDocument.class);
    if (document == null) {
        throw new IllegalArgumentException(String.format("%s header is expected for append operation",
                PDF_DOCUMENT_HEADER_NAME));
    }

    if (document.isEncrypted()) {
        DecryptionMaterial decryptionMaterial = exchange.getIn().getHeader(DECRYPTION_MATERIAL_HEADER_NAME,
                DecryptionMaterial.class);
        if (decryptionMaterial == null) {
            throw new IllegalArgumentException(String.format("%s header is expected for %s operation "
                            + "on encrypted document",
                    DECRYPTION_MATERIAL_HEADER_NAME,
                    pdfConfiguration.getOperation()));
        }

        document.openProtection(decryptionMaterial);
        document.setAllSecurityToBeRemoved(true);
    }

    ProtectionPolicy protectionPolicy = exchange.getIn().getHeader(
            PROTECTION_POLICY_HEADER_NAME, ProtectionPolicy.class);

    appendToPdfDocument(body, document, protectionPolicy);
    OutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    document.save(byteArrayOutputStream);
    return byteArrayOutputStream;
}
 
Example 41
Project: Camel   File: PdfProducer.java   Source Code and License 5 votes vote down vote up
private OutputStream doCreate(Exchange exchange) throws IOException, BadSecurityHandlerException, COSVisitorException {
    LOG.debug("Got {} operation, going to create and write provided string to pdf document.",
            pdfConfiguration.getOperation());
    String body = exchange.getIn().getBody(String.class);
    PDDocument document = new PDDocument();
    StandardProtectionPolicy protectionPolicy = exchange.getIn().getHeader(
            PROTECTION_POLICY_HEADER_NAME, StandardProtectionPolicy.class);
    appendToPdfDocument(body, document, protectionPolicy);
    OutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    document.save(byteArrayOutputStream);
    return byteArrayOutputStream;
}
 
Example 42
Project: pdfboxExamples   File: PdfRuler.java   Source Code and License 5 votes vote down vote up
@Test
public void test() {
	try(MyPDDocument document = this.createNewPDFDocument()) {
		createRulerDocument(document.getUnderlying(), null);
		Path outputFilePath = Files.createTempFile("Test-Ruler", ".pdf");
		document.getUnderlying().save(outputFilePath.toFile());
		logger.info("test# " + outputFilePath.toAbsolutePath().toString());
	} catch (IOException | COSVisitorException e) {
		logger.error("Exception while creating ruler document", e);
		fail(e.getMessage());
	}
}
 
Example 43
Project: testarea-pdfbox1   File: FillFormCustomFont.java   Source Code and License 5 votes vote down vote up
@Test
public void testSetField_acroform() throws IOException, COSVisitorException
{
       try (   InputStream originalStream = getClass().getResourceAsStream("acroform.pdf") )
       {
           PDDocument doc = PDDocument.load(originalStream);

           setField(doc, "FirstName", "My first name");
           setField(doc, "LastName", "My last name");
           
           doc.save(new File(RESULT_FOLDER, "acroform-setField.pdf"));
           doc.close();
       }		
}
 
Example 44
Project: testarea-pdfbox1   File: FillFormCustomFont.java   Source Code and License 5 votes vote down vote up
@Test
public void testSetFieldPMB_acroform() throws IOException, COSVisitorException
{
       try (   InputStream originalStream = getClass().getResourceAsStream("acroform.pdf") )
       {
           PDDocument doc = PDDocument.load(originalStream);

           setFieldBold(doc, "FirstName", "My first name");
           setFieldBold(doc, "LastName", "My last name");
           
           doc.save(new File(RESULT_FOLDER, "acroform-setFieldPMB.pdf"));
           doc.close();
       }		
}
 
Example 45
Project: testarea-pdfbox1   File: FillFormCustomFont.java   Source Code and License 5 votes vote down vote up
@Test
public void testSetFieldFont_acroform() throws IOException, COSVisitorException
{
       try (   InputStream originalStream = getClass().getResourceAsStream("acroform.pdf") )
       {
           PDDocument doc = PDDocument.load(originalStream);
           String fontName = prepareFont(doc);

           setField(doc, "FirstName", "My first name", fontName);
           setField(doc, "LastName", "My last name", fontName);
           
           doc.save(new File(RESULT_FOLDER, "acroform-setFieldFont.pdf"));
           doc.close();
       }		
}
 
Example 46
Project: testarea-pdfbox1   File: FillFormCustomFont.java   Source Code and License 5 votes vote down vote up
@Test
public void testSetFieldCustomBold_acroform() throws IOException, COSVisitorException
{
    try (   InputStream originalStream = getClass().getResourceAsStream("acroform.pdf") )
    {
        PDDocument doc = PDDocument.load(originalStream);
        String fontName = prepareFont(doc);

        setField(doc, "FirstName", "My first name", fontName);
        setFieldBold(doc, "LastName", "My last name");
        
        doc.save(new File(RESULT_FOLDER, "acroform-setFieldCustomBold.pdf"));
        doc.close();
    }
}
 
Example 47
Project: testarea-pdfbox1   File: FillFormCustomFont.java   Source Code and License 5 votes vote down vote up
@Test
public void testSetFieldCustomStandard_acroform() throws IOException, COSVisitorException
{
    try (   InputStream originalStream = getClass().getResourceAsStream("acroform.pdf") )
    {
        PDDocument doc = PDDocument.load(originalStream);
        List<String> fontNames = prepareFont(doc, Arrays.asList(loadTrueTypeFont(doc, "LiberationSans-Regular.ttf"), PDType1Font.HELVETICA_BOLD));

        setField(doc, "FirstName", "My first name", fontNames.get(0));
        setField(doc, "LastName", "My last name", fontNames.get(1));
        
        doc.save(new File(RESULT_FOLDER, "acroform-setFieldCustomStandard.pdf"));
        doc.close();
    }
}
 
Example 48
Project: testarea-pdfbox1   File: AppendFormTwice.java   Source Code and License 5 votes vote down vote up
@Test
public void test() throws COSVisitorException, IOException
{
    byte[] template = generateSimpleTemplate();
    Files.write(new File(RESULT_FOLDER,  "template.pdf").toPath(), template);

    try (   PDDocument finalDoc = new PDDocument(); )
    {
        List<PDField> fields = new ArrayList<PDField>();
        int i = 0;

        for (String value : new String[]{"eins", "zwei"})
        {
            PDDocument doc = new PDDocument().load(new ByteArrayInputStream(template));
            PDDocumentCatalog docCatalog = doc.getDocumentCatalog();
            PDAcroForm acroForm = docCatalog.getAcroForm();
            PDField field = acroForm.getField("SampleField");
            field.setValue(value);
            field.setPartialName("SampleField" + i++);
            List<PDPage> pages = docCatalog.getAllPages();
            finalDoc.addPage(pages.get(0));
            fields.add(field);
        }

        PDAcroForm finalForm = new PDAcroForm(finalDoc);
        finalDoc.getDocumentCatalog().setAcroForm(finalForm);
        finalForm.setFields(fields);

        finalDoc.save(new File(RESULT_FOLDER, "form-two-templates.pdf"));
    }
}
 
Example 49
Project: testarea-pdfbox1   File: NaiveContentEdit.java   Source Code and License 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/29220165/editing-content-in-pdf-using-pdfbox-removes-last-line-from-pdf">
 * Editing content in pdf using PDFBox removes last line from pdf
 * </a>
 * 
 * Reproducing the issue.
 */
@Test
public void testDrunkenfistOriginal() throws IOException, COSVisitorException
{
    try (   InputStream originalStream = getClass().getResourceAsStream("Original.pdf") )
    {
        PDDocument doc = PDDocument.load(originalStream);
        PDPage page = (PDPage) doc.getDocumentCatalog().getAllPages().get(0);
        PDStream contents = page.getContents();
        PDFStreamParser parser = new PDFStreamParser(contents.getStream());
        parser.parse();
        List<Object> tokens = parser.getTokens();
        for (int j = 0; j < tokens.size(); j++) {
            Object next = tokens.get(j);
            if (next instanceof PDFOperator) {
                PDFOperator op = (PDFOperator) next;
                if (op.getOperation().equals("Tj")) {
                    COSString previous = (COSString) tokens.get(j - 1);
                    String string = previous.getString();

                    string = string.replace("@ordnum&", "-ORDERNR-");
                    string = string.replace("@shipid&", "-SHIPMENTID-");
                    string = string.replace("@customer&", "-CUSTOMERNR-");
                    string = string.replace("@fromname&", "-FROMNAME-");

                    tokens.set(j - 1, new COSString(string.trim()));
                }
            }
        }

        PDStream updatedStream = new PDStream(doc);  
        OutputStream out = updatedStream.createOutputStream();  
        ContentStreamWriter tokenWriter = new ContentStreamWriter(out);  
        tokenWriter.writeTokens(tokens);  
        page.setContents(updatedStream);
        
        doc.save(new File(RESULT_FOLDER, "Original-edited.pdf"));
        doc.close();
    }
}
 
Example 50
Project: testarea-pdfbox1   File: RolloverAnnotation.java   Source Code and License 5 votes vote down vote up
@Test
public void testCreateRolloverAnnotation() throws IOException, COSVisitorException
{
    PDAnnotationLink txtLink = new PDAnnotationLink();

    PDActionURI action = new PDActionURI();
    action.setURI("http://www.pdfbox.org");
    txtLink.setAction(action);

    createRollover(txtLink, "rolloverAnnotation.pdf");
}
 
Example 51
Project: testarea-pdfbox1   File: RolloverAnnotation.java   Source Code and License 5 votes vote down vote up
@Test
public void testCreateRolloverButton() throws IOException, COSVisitorException
{
    PDAnnotationWidget widget = new PDAnnotationWidget();
    COSDictionary dictionary = widget.getDictionary();
    dictionary.setName("FT", "Btn");
    dictionary.setInt("Ff", 65536);
    dictionary.setString("T", "Push");

    PDActionURI action = new PDActionURI();
    action.setURI("http://www.pdfbox.org");
    widget.setAction(action);

    createRollover(widget, "rolloverButton.pdf");
}
 
Example 52
Project: testarea-pdfbox1   File: AddValidationRelatedInformation.java   Source Code and License 5 votes vote down vote up
@Test
public void testTestWithImageAndSignature() throws IOException, COSVisitorException, CertificateEncodingException
{
    String resourceName = "testWithImageAndSignature.pdf";
    File resultFile = new File(RESULT_FOLDER, "testWithImageAndSignature-dss.pdf");

    test(resourceName, resultFile);
}
 
Example 53
Project: testarea-pdfbox1   File: AddValidationRelatedInformation.java   Source Code and License 5 votes vote down vote up
@Test
public void test2gFixCertified() throws IOException, COSVisitorException, CertificateEncodingException
{
    String resourceName = "2g-fix-certified.pdf";
    File resultFile = new File(RESULT_FOLDER, "2g-fix-certified-dss.pdf");

    test(resourceName, resultFile);
}
 
Example 54
Project: testarea-pdfbox1   File: OverlayWithEffect.java   Source Code and License 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/29095822/pdfbox-overlay-fails">
 * PDFBox Overlay fails
 * </a>
 *
 * Test using the OPs files
 * https://dl.dropboxusercontent.com/u/21842502/picas/document1.pdf
 * https://dl.dropboxusercontent.com/u/21842502/picas/overlay.pdf
 */
@Test
public void testOverlayWithDarkenVolker() throws COSVisitorException, IOException
{
    try (   InputStream sourceStream = getClass().getResourceAsStream("document1.pdf");
            InputStream overlayStream = getClass().getResourceAsStream("overlay.pdf")  )
    {
        final PDDocument document = PDDocument.load(sourceStream);
        final PDDocument overlay = PDDocument.load(overlayStream);
        
        overlayWithDarkenBlendMode(document, overlay);

        document.save(new File(RESULT_FOLDER, "document1-with-overlay.pdf"));
    }
}
 
Example 55
Project: testarea-pdfbox1   File: OverlayWithEffect.java   Source Code and License 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/29095822/pdfbox-overlay-fails">
 * PDFBox Overlay fails
 * </a>
 *
 * Test using other files.
 */
@Test
public void testOverlayWithDarkenMisc() throws COSVisitorException, IOException
{
    try (   InputStream sourceStream = getClass().getResourceAsStream("test.pdf");
            InputStream overlayStream = getClass().getResourceAsStream("test misplaced.pdf")  )
    {
        final PDDocument document = PDDocument.load(sourceStream);
        final PDDocument overlay = PDDocument.load(overlayStream);
        
        overlayWithDarkenBlendMode(document, overlay);

        document.save(new File(RESULT_FOLDER, "test-with-overlay.pdf"));
    }
}
 
Example 56
Project: testarea-pdfbox1   File: OverlayWithEffect.java   Source Code and License 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/32269571/add-a-watermark-on-a-pdf-that-contains-images-using-pdfbox">
 * Add a watermark on a pdf that contains images using pdfbox
 * </a>
 * <br>
 * <a href="https://drive.google.com/file/d/0B7hG2Ap47MTKMEpqZkpudG1CYjg/view?usp=sharing">
 * pdf-test.pdf
 * </a>
 * <p>
 * Tested overlaying the OP's file with its own page, no issue observed.
 * </p>
 */
@Test
public void testOverlayWithDarkenMarcoAltieri() throws COSVisitorException, IOException
{
    try (   InputStream sourceStream = getClass().getResourceAsStream("pdf-test.pdf");
            InputStream overlayStream = getClass().getResourceAsStream("pdf-test.pdf")  )
    {
        final PDDocument document = PDDocument.load(sourceStream);
        final PDDocument overlay = PDDocument.load(overlayStream);
        
        overlayWithDarkenBlendMode(document, overlay);

        document.save(new File(RESULT_FOLDER, "pdf-test-with-pdf-test.pdf"));
    }
}
 
Example 57
Project: testarea-pdfbox1   File: RenderEndorsement.java   Source Code and License 5 votes vote down vote up
@Test
public void testAlternativeQuick() throws IOException, COSVisitorException
{
    String[] header = new String[]
    {
            "Da�os - Agr�cola y de animales",
            "2015-06-05 / 2016-01-31",
            "FONDO DE ASEGURAMIENTO AGR�COLA 21 DE OCTUBRE",
            "FNP-00004408003772000"
    };

    try (   InputStream logo = getClass().getResourceAsStream("Logo.jpg")   )
    {
        PDDocument document = new PDDocument();
        PdfRenderingEndorsementAlternative renderer = new PdfRenderingEndorsementAlternative(document, logo, header);

        renderer.render(
                new BandColumn(leftHalfPageField, "Nombre del contrato/asegurado:", "Prueba Jesus Fac No Prop"),
                new BandColumn(rightHalfPageField, "Nombre del contrato/asegurado:", "Prueba Jesus Fac No Prop con Endoso")
                );

        renderer.gap(20);

        renderer.render(
                new BandColumn(leftHalfPageField, "Pa�s:", "M�xico"),
                new BandColumn(rightHalfPageField, "Pa�s:", "M�xico")
                );

        renderer.close();
        document.save(new File(RESULT_FOLDER, "EndorsementQuick.pdf"));
    }
}
 
Example 58
Project: testarea-pdfbox1   File: RenderEndorsement.java   Source Code and License 5 votes vote down vote up
@Test
public void testAlternative() throws IOException, COSVisitorException
{
    String[] header = new String[]
    {
            "Da�os - Agr�cola y de animales",
            "2015-06-05 / 2016-01-31",
            "FONDO DE ASEGURAMIENTO AGR�COLA 21 DE OCTUBRE",
            "FNP-00004408003772000"
    };

    try (   InputStream logo = getClass().getResourceAsStream("Logo.jpg")   )
    {
        PDDocument document = new PDDocument();
        PdfRenderingEndorsementAlternative renderer = new PdfRenderingEndorsementAlternative(document, logo, header);

        for (String[] data : SAMPLE_ENDORSEMENT_DATA)
        {
            for (int i = 0; i < data.length - 2; i+=3)
            {
                renderer.render(
                        new BandColumn(leftHalfPageField, data[i+1] != null ? data[i+0] : null, data[i+1]),
                        new BandColumn(rightHalfPageField, data[i+0], data[i+2])
                        );
            }
            renderer.gap(20);
        }

        renderer.close();
        document.save(new File(RESULT_FOLDER, "Endorsement.pdf"));
    }
}
 
Example 59
Project: testarea-pdfbox1   File: RemoveUnderlines.java   Source Code and License 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/34720880/remove-underlines-from-text-in-pdf-file">
 * Remove underlines from text in PDF file
 * </a>
 * <br>
 * <a href="https://www.dropbox.com/s/tkfhkb9e25eby4a/original.pdf?dl=0">
 * original.pdf
 * </a>
 * <p>
 * This test demonstrates how to remove the underlines (i.e. all blue rectangles)
 * from the document.
 * </p>
 */
@Test
public void testOriginal() throws IOException, COSVisitorException
{
    try (   InputStream resourceStream = getClass().getResourceAsStream("original.pdf")   )
    {
        PDDocument document = PDDocument.loadNonSeq(resourceStream, null);

        removeBlueRectangles(document);
        document.save(new File(RESULT_FOLDER, "original-noBlueRectangles.pdf"));
        
        document.close();
    }
}
 
Example 60
Project: testarea-pdfbox1   File: RemoveUnderlines.java   Source Code and License 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/34720880/remove-underlines-from-text-in-pdf-file">
 * Remove underlines from text in PDF file
 * </a>
 * <br>
 * <a href="https://www.dropbox.com/s/23g54bvt781lb93/1178.pdf?dl=0">
 * 1178.pdf
 * </a>
 * <p>
 * This test demonstrates how to remove the underlines (i.e. all blue rectangles)
 * from the second sample document provided by the OP.
 * </p>
 */
@Test
public void test1178() throws IOException, COSVisitorException
{
    try (   InputStream resourceStream = getClass().getResourceAsStream("1178.pdf")   )
    {
        PDDocument document = PDDocument.loadNonSeq(resourceStream, null);

        removeBlueRectangles(document);
        document.save(new File(RESULT_FOLDER, "1178-noBlueRectangles.pdf"));
        
        document.close();
    }
}