Java Code Examples for org.apache.pdfbox.cos.COSName

The following are top voted examples for showing how to use org.apache.pdfbox.cos.COSName. 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: 484_P7_1-Java   File: NurminenDetectionAlgorithm.java   Source Code and License 10 votes vote down vote up
private PDDocument removeText(PDPage page) throws IOException {

        PDFStreamParser parser = new PDFStreamParser(page);
        parser.parse();
        List<Object> tokens = parser.getTokens();
        List<Object> newTokens = new ArrayList<>();
        for (Object token : tokens) {
            if (token instanceof Operator) {
                Operator op = (Operator) token;
                if (op.getName().equals("TJ") || op.getName().equals("Tj")) {
                    //remove the one argument to this operator
                    newTokens.remove(newTokens.size() - 1);
                    continue;
                }
            }
            newTokens.add(token);
        }

        PDDocument document = new PDDocument();
        document.addPage(page);

        PDStream newContents = new PDStream(document);
        OutputStream out = newContents.createOutputStream(COSName.FLATE_DECODE);
        ContentStreamWriter writer = new ContentStreamWriter(out);
        writer.writeTokens(newTokens);
        out.close();
        page.setContents(newContents);

        return document;

    }
 
Example 2
Project: testarea-pdfbox2   File: RenderType3Character.java   Source Code and License 10 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/42032729/render-type3-font-character-as-image-using-pdfbox">
 * Render Type3 font character as image using PDFBox
 * </a>
 * <br/>
 * <a href="https://drive.google.com/file/d/0B0f6X4SAMh2KRDJTbm4tb3E1a1U/view">
 * 4700198773.pdf
 * </a>
 * from
 * <a href="http://stackoverflow.com/questions/37754112/extract-text-with-custom-font-result-non-readble">
 * extract text with custom font result non readble
 * </a>
 * <p>
 * This test shows how one can render individual Type 3 font glyphs as bitmaps.
 * Unfortunately PDFBox out-of-the-box does not provide a class to render contents
 * of arbitrary XObjects, merely for rendering pages; thus, we simply create a page
 * with the glyph in question and render that page.   
 * </p>
 * <p>
 * As the OP did not provide a sample PDF, we simply use one from another
 * stackoverflow question. There obviously might remain issues with the
 * OP's files.
 * </p>
 */
@Test
public void testRenderSdnList() throws IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("sdnlist.pdf"))
    {
        PDDocument document = PDDocument.load(resource);

        PDPage page = document.getPage(1);
        PDResources pageResources = page.getResources();
        COSName f1Name = COSName.getPDFName("R144");
        PDType3Font fontF1 = (PDType3Font) pageResources.getFont(f1Name);
        Map<String, Integer> f1NameToCode = fontF1.getEncoding().getNameToCodeMap();

        COSDictionary charProcsDictionary = fontF1.getCharProcs();
        for (COSName key : charProcsDictionary.keySet())
        {
            COSStream stream = (COSStream) charProcsDictionary.getDictionaryObject(key);
            PDType3CharProc charProc = new PDType3CharProc(fontF1, stream);
            PDRectangle bbox = charProc.getGlyphBBox();
            if (bbox == null)
                bbox = charProc.getBBox();
            Integer code = f1NameToCode.get(key.getName());

            if (code != null)
            {
                PDDocument charDocument = new PDDocument();
                PDPage charPage = new PDPage(bbox);
                charDocument.addPage(charPage);
                charPage.setResources(pageResources);
                PDPageContentStream charContentStream = new PDPageContentStream(charDocument, charPage);
                charContentStream.beginText();
                charContentStream.setFont(fontF1, bbox.getHeight());
                charContentStream.getOutput().write(String.format("<%2X> Tj\n", code).getBytes());
                charContentStream.endText();
                charContentStream.close();

                File result = new File(RESULT_FOLDER, String.format("sdnlist-%s-%s.png", key.getName(), code));
                PDFRenderer renderer = new PDFRenderer(charDocument);
                BufferedImage image = renderer.renderImageWithDPI(0, 96);
                ImageIO.write(image, "PNG", result);
                charDocument.save(new File(RESULT_FOLDER, String.format("sdnlist-%s-%s.pdf", key.getName(), code)));
                charDocument.close();
            }
        }
    }
}
 
Example 3
Project: testarea-pdfbox2   File: RemoveStrikeoutComment.java   Source Code and License 8 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/45812696/pdfbox-delete-comment-maintain-strikethrough">
 * PDFBox delete comment maintain strikethrough
 * </a>
 * <br/>
 * <a href="https://expirebox.com/files/3d955e6df4ca5874c38dbf92fc43b5af.pdf">
 * only_fields.pdf
 * </a>
 * <a href="https://file.io/DTvqhC">
 * (alternative download)
 * </a>
 * <p>
 * The OP only wanted the comment removed, not the strike-through. Thus, we must
 * not remove the annotation but merely the comment building attributes.
 * </p>
 */
@Test
public void testRemoveLikeStephanImproved() throws IOException {
    final COSName POPUP = COSName.getPDFName("Popup");
    try (InputStream resource = getClass().getResourceAsStream("only_fields.pdf")) {
        PDDocument document = PDDocument.load(resource);
        List<PDAnnotation> annotations = new ArrayList<>();
        PDPageTree allPages = document.getDocumentCatalog().getPages();

        List<COSObjectable> objectsToRemove = new ArrayList<>();

        for (int i = 0; i < allPages.getCount(); i++) {
            PDPage page = allPages.get(i);
            annotations = page.getAnnotations();

            for (PDAnnotation annotation : annotations) {
                if ("StrikeOut".equals(annotation.getSubtype()))
                {
                    COSDictionary annotationDict = annotation.getCOSObject();
                    COSBase popup = annotationDict.getItem(POPUP);
                    annotationDict.removeItem(POPUP);
                    annotationDict.removeItem(COSName.CONTENTS); // plain text comment
                    annotationDict.removeItem(COSName.RC);       // rich text comment
                    annotationDict.removeItem(COSName.T);        // author

                    if (popup != null)
                        objectsToRemove.add(popup);
                }
            }

            annotations.removeAll(objectsToRemove);
        }

        document.save(new File(RESULT_FOLDER, "only_fields-removeImproved.pdf"));
    }
}
 
Example 4
Project: testarea-pdfbox2   File: RenderType3Character.java   Source Code and License 8 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/42032729/render-type3-font-character-as-image-using-pdfbox">
 * Render Type3 font character as image using PDFBox
 * </a>
 * <br/>
 * <a href="https://drive.google.com/file/d/0B0f6X4SAMh2KRDJTbm4tb3E1a1U/view">
 * 4700198773.pdf
 * </a>
 * from
 * <a href="http://stackoverflow.com/questions/37754112/extract-text-with-custom-font-result-non-readble">
 * extract text with custom font result non readble
 * </a>
 * <p>
 * This test shows how one can render individual Type 3 font glyphs as bitmaps.
 * Unfortunately PDFBox out-of-the-box does not provide a class to render contents
 * of arbitrary XObjects, merely for rendering pages; thus, we simply create a page
 * with the glyph in question and render that page.   
 * </p>
 * <p>
 * As the OP did not provide a sample PDF, we simply use one from another
 * stackoverflow question. There obviously might remain issues with the
 * OP's files.
 * </p>
 */
@Test
public void testRender4700198773() throws IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("4700198773.pdf"))
    {
        PDDocument document = PDDocument.load(resource);

        PDPage page = document.getPage(0);
        PDResources pageResources = page.getResources();
        COSName f1Name = COSName.getPDFName("F1");
        PDType3Font fontF1 = (PDType3Font) pageResources.getFont(f1Name);
        Map<String, Integer> f1NameToCode = fontF1.getEncoding().getNameToCodeMap();

        COSDictionary charProcsDictionary = fontF1.getCharProcs();
        for (COSName key : charProcsDictionary.keySet())
        {
            COSStream stream = (COSStream) charProcsDictionary.getDictionaryObject(key);
            PDType3CharProc charProc = new PDType3CharProc(fontF1, stream);
            PDRectangle bbox = charProc.getGlyphBBox();
            if (bbox == null)
                bbox = charProc.getBBox();
            Integer code = f1NameToCode.get(key.getName());

            if (code != null)
            {
                PDDocument charDocument = new PDDocument();
                PDPage charPage = new PDPage(bbox);
                charDocument.addPage(charPage);
                charPage.setResources(pageResources);
                PDPageContentStream charContentStream = new PDPageContentStream(charDocument, charPage);
                charContentStream.beginText();
                charContentStream.setFont(fontF1, bbox.getHeight());
                charContentStream.getOutput().write(String.format("<%2X> Tj\n", code).getBytes());
                charContentStream.endText();
                charContentStream.close();

                File result = new File(RESULT_FOLDER, String.format("4700198773-%s-%s.png", key.getName(), code));
                PDFRenderer renderer = new PDFRenderer(charDocument);
                BufferedImage image = renderer.renderImageWithDPI(0, 96);
                ImageIO.write(image, "PNG", result);
                charDocument.save(new File(RESULT_FOLDER, String.format("4700198773-%s-%s.pdf", key.getName(), code)));
                charDocument.close();
            }
        }
    }
}
 
Example 5
Project: IDBuilderFX   File: ExtractPhoto.java   Source Code and License 7 votes vote down vote up
public static void findPhoto(String path,int empId) throws IOException, SQLException, Error{
		// Loading an existing document
		int imageFound=0;
		File file = new File(path);
		PDDocument document=PDDocument.load(file);
		PDPageTree list=document.getPages();
		for(PDPage page:list){						//check in all pages of pdf
			PDResources pdResources=page.getResources();		//get all resources
			for(COSName cosName:pdResources.getXObjectNames())		//loop for all resources
			{
				PDXObject pdxObject=pdResources.getXObject(cosName);
				 if (pdxObject instanceof PDImageXObject) {			//check that the resource is image
		                BufferedImage br=((PDImageXObject) pdxObject).getImage();
		                RgbImage im = RgbImageJ2se.toRgbImage(br);
		                // step #3 - convert image to greyscale 8-bits
		                RgbAvgGray toGray = new RgbAvgGray();
		                toGray.push(im);
		                // step #4 - initialize face detector with correct Haar profile
		                InputStream is  = ExtractPhoto.class.getResourceAsStream("/haar/HCSB.txt");
		                Gray8DetectHaarMultiScale detectHaar = new Gray8DetectHaarMultiScale(is, 1,40);
		                // step #5 - apply face detector to grayscale image
		                List<Rect> result= detectHaar.pushAndReturn(toGray.getFront());
		                if(result.size()!=0)
		                {
		                database.StorePhoto.storePhoto(empId,br);
		                imageFound=1;
		                break;
		                }
				 }
			}
			if(imageFound==1)
				break;
}
		System.out.println(imageFound);
		if(imageFound!=1){
			BufferedImage in = ImageIO.read(ExtractPhoto.class.getResource("/images/nopic.jpg"));
            database.StorePhoto.storePhoto(empId,in);
		}
	document.close();	
	}
 
Example 6
Project: oma-riista-web   File: HunterPaymentPdfFeature.java   Source Code and License 7 votes vote down vote up
public byte[] build() throws IOException {
    this.acroForm.setNeedAppearances(false);

    // Fix annotations
    for (PDPage page : this.pdfDocument.getPages()) {
        for (PDAnnotation annot : page.getAnnotations()) {
            annot.setPage(page);
        }
    }

    // Define font resources names used in PDF template
    final PDResources dr = new PDResources();
    dr.put(COSName.getPDFName("Helv"), PDType1Font.HELVETICA);
    dr.put(COSName.getPDFName("HeBo"), PDType1Font.HELVETICA_BOLD);
    this.acroForm.setDefaultResources(dr);

    // Convert form fields to text
    this.acroForm.flatten();

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    pdfDocument.save(bos);
    pdfDocument.close();
    return bos.toByteArray();
}
 
Example 7
Project: pdf-box-examples   File: PdfImagesHelper.java   Source Code and License 7 votes vote down vote up
private List<RenderedImage> getImagesFromResources(PDResources resources) throws IOException {

        List<RenderedImage> images = new ArrayList<>();
        for (COSName xObjectName : resources.getXObjectNames()) {
            PDXObject xObject = resources.getXObject(xObjectName);
            if (xObject instanceof PDImageXObject) {
                images.add(((PDImageXObject) xObject).getImage());
            } else if (xObject instanceof PDFormXObject) {
                images.addAll(getImagesFromResources(((PDFormXObject) xObject).getResources()));
            }
        }
        return images;
    }
 
Example 8
Project: icecite   File: SetGraphicsStateParameters.java   Source Code and License 7 votes vote down vote up
@Override
public void process(Operator operator, List<COSBase> arguments)
  throws IOException {
  // set parameters from graphics state parameter dictionary
  COSName dictName = (COSName) arguments.get(0);
  PDExtendedGraphicsState gs = context.getResources().getExtGState(dictName);
  gs.copyIntoGraphicsState(context.getGraphicsState());
}
 
Example 9
Project: icecite   File: SetNonStrokingDeviceRGBColor.java   Source Code and License 7 votes vote down vote up
@Override
public void process(Operator operator, List<COSBase> arguments)
  throws IOException {
  PDColorSpace cs = context.getResources().getColorSpace(COSName.DEVICERGB);
  context.getGraphicsState().setNonStrokingColorSpace(cs);
  super.process(operator, arguments);
}
 
Example 10
Project: testarea-pdfbox1   File: CreateCheckbox.java   Source Code and License 7 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/43604973/creating-a-checkbox-and-printing-it-to-pdf-file-is-not-working-using-pdfbox-1-8">
 * Creating a checkbox and printing it to pdf file is not working using pdfbox 1.8.9 api
 * </a>
 * <p>
 * The OP's method for checkbox creation.
 * </p>
 * @see #testCheckboxLikeSureshGoud()
 */
public static void writeInputFieldToPDFPage( PDPage pdPage, PDDocument document, Float x, Float y, Boolean ticked) throws IOException {
    PDFont font = PDType1Font.HELVETICA;
    PDResources res = new PDResources();
    String fontName = res.addFont(font);
    String da = ticked?"/" + fontName + " 10 Tf 0 0.4 0 rg":"";

    COSDictionary acroFormDict = new COSDictionary();
    acroFormDict.setBoolean(COSName.getPDFName("NeedAppearances"), true);
    acroFormDict.setItem(COSName.FIELDS, new COSArray());
    acroFormDict.setItem(COSName.DA, new COSString(da));

    PDAcroForm acroForm =  new PDAcroForm(document, acroFormDict);
    acroForm.setDefaultResources(res);
    document.getDocumentCatalog().setAcroForm(acroForm);

    PDGamma colourBlack = new PDGamma();
    PDAppearanceCharacteristicsDictionary fieldAppearance =
        new PDAppearanceCharacteristicsDictionary(new COSDictionary());
    fieldAppearance.setBorderColour(colourBlack);
    if(ticked) {
        COSArray arr = new COSArray();
        arr.add(new COSFloat(0.89f));
        arr.add(new COSFloat(0.937f));
        arr.add(new COSFloat(1f));
        fieldAppearance.setBackground(new PDGamma(arr));
    }

    COSDictionary cosDict = new COSDictionary();
    COSArray rect = new COSArray();

    rect.add(new COSFloat(x));
    rect.add(new COSFloat(new Float(y-5)));
    rect.add(new COSFloat(new Float(x+10)));
    rect.add(new COSFloat(new Float(y+5)));

    cosDict.setItem(COSName.RECT, rect);
    cosDict.setItem(COSName.FT, COSName.getPDFName("Btn")); // Field Type
    cosDict.setItem(COSName.TYPE, COSName.ANNOT);
    cosDict.setItem(COSName.SUBTYPE, COSName.getPDFName("Widget"));
    if(ticked) {
        cosDict.setItem(COSName.TU, new COSString("Checkbox with PDFBox"));
    }
    cosDict.setItem(COSName.T, new COSString("Chk"));
    //Tick mark color and size of the mark
    cosDict.setItem(COSName.DA, new COSString(ticked?"/F0 10 Tf 0 0.4 0 rg":"/FF 1 Tf 0 0 g"));
    cosDict.setInt(COSName.F, 4);

    PDCheckbox checkbox = new PDCheckbox(acroForm, cosDict);
    checkbox.setFieldFlags(PDCheckbox.FLAG_READ_ONLY);
    checkbox.setValue("Yes");

    checkbox.getWidget().setAppearanceCharacteristics(fieldAppearance);

    pdPage.getAnnotations().add(checkbox.getWidget());
    acroForm.getFields().add(checkbox);
}
 
Example 11
Project: pdfbox-graphics2d   File: PdfBoxGraphics2D.java   Source Code and License 6 votes vote down vote up
/**
 * @param document
 *            The document the graphics should be used to create a XForm in.
 * @param bbox
 *            Bounding Box of the graphics
 * @throws IOException
 *             when something goes wrong with writing into the content
 *             stream of the {@link PDDocument}.
 */
public PdfBoxGraphics2D(PDDocument document, PDRectangle bbox) throws IOException {
	this.document = document;
	this.bbox = bbox;

	PDAppearanceStream appearance = new PDAppearanceStream(document);
	xFormObject = appearance;
	xFormObject.setResources(new PDResources());
	xFormObject.setBBox(bbox);
	contentStream = new PDPageContentStream(document, appearance, xFormObject.getStream().createOutputStream(COSName.FLATE_DECODE));
	contentStreamSaveState();

	baseTransform = new AffineTransform();
	baseTransform.translate(0, bbox.getHeight());
	baseTransform.scale(1, -1);

	calcImage = new BufferedImage(100, 100, BufferedImage.TYPE_4BYTE_ABGR);
	calcGfx = calcImage.createGraphics();
	font = calcGfx.getFont();
	cloneInfo = null;
}
 
Example 12
Project: pdfbox   File: PdfImageCounter.java   Source Code and License 6 votes vote down vote up
public PdfImageCounter() {
    addOperator(new OperatorProcessor() {
        @Override
        public void process(Operator operator, List<COSBase> arguments) throws IOException {
            if (arguments.size() < 1) {
                throw new org.apache.pdfbox.contentstream.operator.MissingOperandException(operator, arguments);
            }
            if (isImage(arguments.get(0))) {
                documentImageCount++;
            }
        }

        protected Boolean isImage(COSBase base) {
            return (base instanceof COSName) &&
                    context.getResources().isImageXObject((COSName)base);
        }

        @Override
        public String getName() {
            return "Do";
        }
    });
}
 
Example 13
Project: ctsms   File: PDFUtil.java   Source Code and License 6 votes vote down vote up
private static void drawString(PDPageContentStream contentStream, String text) throws IOException {
	if (contentStream != null && text != null && text.length() > 0) {
		char[] tc = text.toCharArray();
		StringBuilder sb = new StringBuilder();
		Encoding encoding = EncodingManager.INSTANCE.getEncoding(COSName.WIN_ANSI_ENCODING);
		for (int i = 0; i < tc.length; i++) {
			Character c = tc[i];
			try {
				sb.appendCodePoint(encoding.getCode(encoding.getNameFromCharacter(c)));
			} catch (IOException e) {
				sb.append(c);
			}
		}
		contentStream.drawString(sb.toString());
	}
}
 
Example 14
Project: memoria-politica   File: FedDepPhotosUtility.java   Source Code and License 6 votes vote down vote up
private static void buildImgKeyToPolNameMapping(PDPage page) throws IOException {
    PDStream contents = page.getContents();
    PDFStreamParser parser = new PDFStreamParser(contents.getStream());
    parser.parse();
    List tokens = parser.getTokens();

    boolean concatStringPhase = false;
    String polName = "";
    String lastText = "";

    for (int index = 0; index < tokens.size(); index++) {
        Object obj = tokens.get(index);

        if (obj instanceof PDFOperator) {
            PDFOperator op = (PDFOperator) obj;
            if (op.getOperation().equals("BT")) {
                concatStringPhase = true;
                polName = lastText;
                lastText = "";
            }
            else if (op.getOperation().equals("ET")) {
                concatStringPhase = false;
            }
        }
        else if (concatStringPhase && obj instanceof COSString) {
            COSString cosString = (COSString) obj;
            lastText += " " + cosString.getString();
            lastText = lastText.trim();
        }
        else if (!concatStringPhase && obj instanceof COSName) {
            COSName cosName = (COSName) obj;
            if (cosName.getName().startsWith("img")) {
                mapImgKeyToPolName.put(cosName.getName(), polName);
            }
        }
    }
}
 
Example 15
Project: FontVerter   File: PdfFontExtractor.java   Source Code and License 6 votes vote down vote up
private void extractFontResources(PDResources resources) throws IOException {
    for (COSName key : resources.getFontNames()) {
        PDFont font = resources.getFont(key);
        extractStrategy.extract(font);
    }

    for (COSName name : resources.getXObjectNames()) {
        PDXObject xobject = resources.getXObject(name);
        if (xobject instanceof PDFormXObject) {
            PDFormXObject xObjectForm = (PDFormXObject) xobject;
            PDResources formResources = xObjectForm.getResources();

            if (formResources != null)
                extractFontResources(formResources);
        }
    }
}
 
Example 16
Project: testarea-pdfbox2   File: HelloSignAnalyzer.java   Source Code and License 6 votes vote down vote up
@Override
protected void processOperator(Operator operator, List<COSBase> operands) throws IOException
{
    String currentFormName = formName; 
    if (operator != null && "Do".equals(operator.getName()) && operands != null && operands.size() > 0)
    {
        COSBase base0 = operands.get(0);
        if (base0 instanceof COSName)
        {
            formName = ((COSName)base0).getName();
            if (currentFormName == null)
                lastFormName = formName;
        }
    }
    try
    {
        super.processOperator(operator, operands);
    }
    finally
    {
        formName = currentFormName;
    }
}
 
Example 17
Project: testarea-pdfbox2   File: CreatePortableCollection.java   Source Code and License 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/46642994/how-to-create-pdf-package-using-pdfbox">
 * How to create pdf package using PdfBox?
 * </a>
 * <p>
 * This test implements the equivalent of the OP's code turning
 * a regular PDF into a portable collection.
 * </p>
 */
@Test
public void test() throws IOException {
    try (   InputStream resource = getClass().getResourceAsStream("/mkl/testarea/pdfbox2/sign/test.pdf"))
    {
        PDDocument pdDocument = PDDocument.load(resource);

        COSDictionary collectionDictionary = new COSDictionary();
        collectionDictionary.setName(COSName.TYPE, "Collection");
        collectionDictionary.setName("View", "T");
        PDDocumentCatalog catalog = pdDocument.getDocumentCatalog();
        catalog.getCOSObject().setItem("Collection", collectionDictionary);

        pdDocument.save(new File(RESULT_FOLDER, "test-collection.pdf"));
    }
}
 
Example 18
Project: testarea-pdfbox2   File: ReadForm.java   Source Code and License 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/36964496/pdfbox-2-0-overcoming-dictionary-key-encoding">
 * PDFBox 2.0: Overcoming dictionary key encoding
 * </a>
 * <br/>
 * <a href="http://www.stockholm.se/PageFiles/85478/KYF%20211%20Best%C3%A4llning%202014.pdf">
 * KYF 211 Best&auml;llning 2014.pdf
 * </a>
 * 
 * <p>
 * Indeed, the special characters in the names are replaced by the Unicode replacement
 * character. PDFBox, when parsing a PDF name, immediately interprets its bytes as UTF-8
 * encoded which fails in the document at hand.
 * </p>
 */
@Test
public void testReadFormOptions() throws IOException
{
    try (   InputStream originalStream = getClass().getResourceAsStream("KYF 211 Best\u00e4llning 2014.pdf") )
    {
        PDDocument pdfDocument = PDDocument.load(originalStream);
        PDAcroForm acroForm = pdfDocument.getDocumentCatalog().getAcroForm();
        
        PDField field = acroForm.getField("Krematorier");
        List<PDAnnotationWidget> widgets = field.getWidgets();
        System.out.println("Field Name: " + field.getPartialName() + " (" + widgets.size() + ")");
        for (PDAnnotationWidget annot : widgets) {
          PDAppearanceDictionary ap = annot.getAppearance();
          Set<COSName> keys = ((COSDictionary)(ap.getCOSObject().getDictionaryObject("N"))).keySet();
          ArrayList<String> keyList = new ArrayList<>(keys.size());
          for (COSName cosKey : keys) {keyList.add(cosKey.getName());}
          System.out.println(String.join("|", keyList));
        }
    }
}
 
Example 19
Project: testarea-pdfbox2   File: TestEmptySignatureField.java   Source Code and License 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/37601092/pdfbox-identify-specific-pages-and-functionalities-recommendations">
 * PDFBox identify specific pages and functionalities recommendations
 * </a>
 * 
 * <p>
 * This test shows how to add an empty signature field with a custom appearance
 * to an existing PDF.
 * </p>
 */
@Test
public void testAddEmptySignatureField() throws IOException
{
    try (   InputStream sourceStream = getClass().getResourceAsStream("test.pdf");
            OutputStream output = new FileOutputStream(new File(RESULT_FOLDER, "test-with-empty-sig-field.pdf")))
    {
        PDFont font = PDType1Font.HELVETICA;
        PDResources resources = new PDResources();
        resources.put(COSName.getPDFName("Helv"), font);

        PDDocument document = PDDocument.load(sourceStream);
        PDAcroForm acroForm = new PDAcroForm(document);
        acroForm.setDefaultResources(resources);
        document.getDocumentCatalog().setAcroForm(acroForm);

        PDRectangle rect = new PDRectangle(50, 750, 200, 50);

        PDAppearanceDictionary appearanceDictionary = new PDAppearanceDictionary();
        PDAppearanceStream appearanceStream = new PDAppearanceStream(document);
        appearanceStream.setBBox(rect.createRetranslatedRectangle());
        appearanceStream.setResources(resources);
        appearanceDictionary.setNormalAppearance(appearanceStream);
        PDPageContentStream contentStream = new PDPageContentStream(document, appearanceStream);
        contentStream.setStrokingColor(Color.BLACK);
        contentStream.setNonStrokingColor(Color.LIGHT_GRAY);
        contentStream.setLineWidth(2);
        contentStream.addRect(0, 0, rect.getWidth(), rect.getHeight());
        contentStream.fill();
        contentStream.moveTo(1 * rect.getHeight() / 4, 1 * rect.getHeight() / 4);
        contentStream.lineTo(2 * rect.getHeight() / 4, 3 * rect.getHeight() / 4);
        contentStream.moveTo(1 * rect.getHeight() / 4, 3 * rect.getHeight() / 4);
        contentStream.lineTo(2 * rect.getHeight() / 4, 1 * rect.getHeight() / 4);
        contentStream.moveTo(3 * rect.getHeight() / 4, 1 * rect.getHeight() / 4);
        contentStream.lineTo(rect.getWidth() - rect.getHeight() / 4, 1 * rect.getHeight() / 4);
        contentStream.stroke();
        contentStream.setNonStrokingColor(Color.DARK_GRAY);
        contentStream.beginText();
        contentStream.setFont(font, rect.getHeight() / 5);
        contentStream.newLineAtOffset(3 * rect.getHeight() / 4, -font.getBoundingBox().getLowerLeftY() * rect.getHeight() / 5000);
        contentStream.showText("Customer");
        contentStream.endText();
        contentStream.close();

        PDSignatureField signatureField = new PDSignatureField(acroForm);
        signatureField.setPartialName("SignatureField");
        PDPage page = document.getPage(0);

        PDAnnotationWidget widget = signatureField.getWidgets().get(0);
        widget.setAppearance(appearanceDictionary);
        widget.setRectangle(rect);
        widget.setPage(page);

        page.getAnnotations().add(widget);
        acroForm.getFields().add(signatureField);

        document.save(output);
        document.close();
    }
}
 
Example 20
Project: testarea-pdfbox2   File: ExtractImages.java   Source Code and License 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/40531871/how-can-i-check-if-pdf-page-is-imagescanned-by-pdfbox-xpdf">
 * How can I check if PDF page is image(scanned) by PDFBOX, XPDF
 * </a>
 * <br/>
 * <a href="https://drive.google.com/file/d/0B9izTHWJQ7xlT2ZoQkJfbGRYcFE">
 * 10948.pdf
 * </a>
 * <p>
 * The only special thing about the two images returned for the sample PDF is that
 * one image is merely a mask used for the other image, and the other image is the
 * actual image used on the PDF page. If one only wants the images immediately used
 * in the page content, one also has to scan the page content.
 * </p>
 */
@Test
public void testExtractPageImageResources10948() throws IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("10948.pdf"))
    {
        PDDocument document = PDDocument.load(resource);
        int page = 1;
        for (PDPage pdPage : document.getPages())
        {
            PDResources resources = pdPage.getResources();
            if (resource != null)
            {
                int index = 0;
                for (COSName cosName : resources.getXObjectNames())
                {
                    PDXObject xobject = resources.getXObject(cosName);
                    if (xobject instanceof PDImageXObject)
                    {
                        PDImageXObject image = (PDImageXObject)xobject;
                        File file = new File(RESULT_FOLDER, String.format("10948-%s-%s.%s", page, index, image.getSuffix()));
                        ImageIO.write(image.getImage(), image.getSuffix(), file);
                        index++;
                    }
                }
            }
            page++;
        }
    }
}
 
Example 21
Project: testarea-pdfbox2   File: ExtractImages.java   Source Code and License 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/40531871/how-can-i-check-if-pdf-page-is-imagescanned-by-pdfbox-xpdf">
 * How can I check if PDF page is image(scanned) by PDFBOX, XPDF
 * </a>
 * <br/>
 * <a href="https://drive.google.com/open?id=0B9izTHWJQ7xlYi1XN1BxMmZEUGc">
 * 10948.pdf
 * </a>, renamed "10948-new.pdf" here to prevent a collision
 * <p>
 * Here the code extracts no image at all because the images are not immediate page
 * resources but wrapped in form xobjects.
 * </p>
 */
@Test
public void testExtractPageImageResources10948New() throws IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("10948-new.pdf"))
    {
        PDDocument document = PDDocument.load(resource);
        int page = 1;
        for (PDPage pdPage : document.getPages())
        {
            PDResources resources = pdPage.getResources();
            if (resource != null)
            {
                int index = 0;
                for (COSName cosName : resources.getXObjectNames())
                {
                    PDXObject xobject = resources.getXObject(cosName);
                    if (xobject instanceof PDImageXObject)
                    {
                        PDImageXObject image = (PDImageXObject)xobject;
                        File file = new File(RESULT_FOLDER, String.format("10948-new-%s-%s.%s", page, index, image.getSuffix()));
                        ImageIO.write(image.getImage(), image.getSuffix(), file);
                        index++;
                    }
                }
            }
            page++;
        }
    }
}
 
Example 22
Project: pdf-box-examples   File: PdfImagesHelper.java   Source Code and License 6 votes vote down vote up
private void drawXObject(PDImageXObject xobject, PDResources resources, OutputStream os,
                         float x, float y, float width, float height) throws IOException {
    // This is similar to PDPageContentStream.drawXObject()
    COSName xObjectId = resources.add(xobject);

    appendRawCommands(os, SAVE_GRAPHICS_STATE);
    appendRawCommands(os, formatDecimal.format(width));
    appendRawCommands(os, SPACE);
    appendRawCommands(os, formatDecimal.format(0));
    appendRawCommands(os, SPACE);
    appendRawCommands(os, formatDecimal.format(0));
    appendRawCommands(os, SPACE);
    appendRawCommands(os, formatDecimal.format(height));
    appendRawCommands(os, SPACE);
    appendRawCommands(os, formatDecimal.format(x));
    appendRawCommands(os, SPACE);
    appendRawCommands(os, formatDecimal.format(y));
    appendRawCommands(os, SPACE);
    appendRawCommands(os, CONCATENATE_MATRIX);
    appendRawCommands(os, SPACE);
    appendRawCommands(os, "/");
    appendRawCommands(os, xObjectId.getName());
    appendRawCommands(os, SPACE);
    appendRawCommands(os, XOBJECT_DO);
    appendRawCommands(os, SPACE);
    appendRawCommands(os, RESTORE_GRAPHICS_STATE);
}
 
Example 23
Project: pdfdigisign   File: Verificator.java   Source Code and License 6 votes vote down vote up
/**
 * Validates the PDF file specified in the constructor
 * @return PDFDocumentInfo structure
 **/
public PDFDocumentInfo validate() throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException {
  String infoString = null;
  PDDocument document = null;
  try {
    document = PDDocument.load(new File(path));

    COSDictionary trailer = document.getDocument().getTrailer();
    COSDictionary root = (COSDictionary) trailer.getDictionaryObject(COSName.ROOT);
    COSDictionary acroForm = (COSDictionary) root.getDictionaryObject(COSName.ACRO_FORM);
    if (acroForm == null) {
      return doc;
    }
    COSArray fields = (COSArray) acroForm.getDictionaryObject(COSName.FIELDS);

    for (int i = 0; i < fields.size(); i ++) {
      COSDictionary field = (COSDictionary) fields.getObject(i);

      COSName type = field.getCOSName(COSName.FT);
      if (COSName.SIG.equals(type)) {
        COSDictionary sig = (COSDictionary) field.getDictionaryObject(COSName.V);
        if (sig != null) {
          getSignatureInfo(sig);
        }
      }
    }
  }
  finally {
    if (document != null) {
      document.close();
    }
  }
  return doc;
}
 
Example 24
Project: icecite   File: BeginInlineImage.java   Source Code and License 6 votes vote down vote up
/**
   * process : BI : begin inline image.
   * 
   * @param operator
   *          The operator that is being executed.
   * @param arguments
   *          List
   * @throws IOException
   *           If there is an error displaying the inline image.
   */
  public void process(Operator operator, List<COSBase> arguments)
    throws IOException {
    Matrix ctm = context.getCurrentTransformationMatrix();
    COSDictionary params = operator.getImageParameters();
    
    int width = params.getInt(COSName.W, COSName.WIDTH, -1);
    int height = params.getInt(COSName.H, COSName.HEIGHT, -1);
    
    // TODO: use transform().

    float minX = ctm.getTranslateX();
    float maxX = minX + (width * ctm.getScaleX());
    float minY = ctm.getTranslateY();
    float maxY = minY + (height * ctm.getScaleY());

    // Type3 streams may contain BI operands, but we don't wan't to consider
    // those.
    if (!context.isType3Stream()) {
//      Rectangle boundBox = new SimpleRectangle(minX, minY, maxX, maxY);
      
      Rectangle boundBox = SimpleRectangle.from2Vertices(
          new SimplePoint(minX, minY), 
          new SimplePoint(maxX, maxY));
      
      PDImage image = new PDInlineImage(operator.getImageParameters(),
          operator.getImageData(), context.getResources());
      
      PdfBoxColor exclusiveColor = getExclusiveColor(image.getImage());
      
      if (exclusiveColor != null) {
        PdfBoxShape shape = new PdfBoxShape(context.getCurrentPage());
        shape.setRectangle(boundBox);
        shape.setColor(exclusiveColor);
        context.showShape(shape);
      } else {
        PdfBoxFigure figure = new PdfBoxFigure(context.getCurrentPage());
        figure.setRectangle(boundBox);
        context.showFigure(figure);
      }
    }
  }
 
Example 25
Project: testarea-pdfbox1   File: FillFormCustomFont.java   Source Code and License 6 votes vote down vote up
public static void setField(PDDocument _pdfDocument, String name, String value) throws IOException
{
	PDDocumentCatalog docCatalog = _pdfDocument.getDocumentCatalog();
	PDAcroForm acroForm = docCatalog.getAcroForm();
	PDField field = acroForm.getField(name);

	COSDictionary dict = ((PDField) field).getDictionary();
	COSString defaultAppearance = (COSString) dict
			.getDictionaryObject(COSName.DA);
	if (defaultAppearance != null)
	{
		dict.setString(COSName.DA, "/Helv 10 Tf 0 g");
		if (name.equalsIgnoreCase("Field1")) {
			dict.setString(COSName.DA, "/Helv 12 Tf 0 g");
		}
	}
	if (field instanceof PDTextbox)
	{
		field = new PDTextbox(acroForm, dict);
		((PDField) field).setValue(value);
	}
}
 
Example 26
Project: testarea-pdfbox1   File: FillFormCustomFont.java   Source Code and License 6 votes vote down vote up
public static void setFieldBold(PDDocument _pdfDocument, String name, String value) throws IOException
{
	PDDocumentCatalog docCatalog = _pdfDocument.getDocumentCatalog();
	PDAcroForm acroForm = docCatalog.getAcroForm();
	PDField field = acroForm.getField(name);

	COSDictionary dict = ((PDField) field).getDictionary();
	COSString defaultAppearance = (COSString) dict
			.getDictionaryObject(COSName.DA);
	if (defaultAppearance != null)
	{
		dict.setString(COSName.DA, "/Helv 10 Tf 2 Tr .5 w 0 g");
		if (name.equalsIgnoreCase("Field1")) {
			dict.setString(COSName.DA, "/Helv 12 Tf 0 g");
		}
	}
	if (field instanceof PDTextbox)
	{
		field = new PDTextbox(acroForm, dict);
		((PDField) field).setValue(value);
	}
}
 
Example 27
Project: testarea-pdfbox1   File: FillFormCustomFont.java   Source Code and License 6 votes vote down vote up
public static void setField(PDDocument _pdfDocument, String name, String value, String fontName) throws IOException
{
	PDDocumentCatalog docCatalog = _pdfDocument.getDocumentCatalog();
	PDAcroForm acroForm = docCatalog.getAcroForm();
	PDField field = acroForm.getField(name);

	COSDictionary dict = ((PDField) field).getDictionary();
	COSString defaultAppearance = (COSString) dict
			.getDictionaryObject(COSName.DA);
	if (defaultAppearance != null)
	{
		dict.setString(COSName.DA, "/" + fontName + " 10 Tf 0 g");
		if (name.equalsIgnoreCase("Field1")) {
			dict.setString(COSName.DA, "/" + fontName + " 12 Tf 0 g");
		}
	}
	if (field instanceof PDTextbox)
	{
		field = new PDTextbox(acroForm, dict);
		((PDField) field).setValue(value);
	}
}
 
Example 28
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 29
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 30
Project: testarea-pdfbox1   File: UnderlayText.java   Source Code and License 6 votes vote down vote up
/**
 * This method on each page moves the last content stream
 * to the second position.
 */
void pushUnder(PDDocument document)
{
    List<?> pages = document.getDocumentCatalog().getAllPages();
    float fontSize = 70.0f;
    for (int i = 0; i < pages.size(); i++) {
        PDPage page = (PDPage) pages.get(i);
        COSBase contents = page.getCOSDictionary().getDictionaryObject(COSName.CONTENTS);
        if (contents instanceof COSStreamArray)
        {
            COSStreamArray contentsArray = (COSStreamArray) contents;
            COSArray newArray = new COSArray();
            newArray.add(contentsArray.get(0));
            newArray.add(contentsArray.get(contentsArray.getStreamCount() - 1));

            for (int j = 1; j < contentsArray.getStreamCount() - 1; j++)
            {
                newArray.add(contentsArray.get(j));
            }

            COSStreamArray newStreamArray = new COSStreamArray(newArray);
            page.getCOSDictionary().setItem(COSName.CONTENTS, newStreamArray);
        }
    }
}
 
Example 31
Project: testarea-pdfbox1   File: ExtractPatternImages.java   Source Code and License 6 votes vote down vote up
public void extractPatternImages(PDPatternResources pattern, String patternFormat) throws IOException
{
    COSDictionary resourcesDict = (COSDictionary) pattern.getCOSDictionary().getDictionaryObject(COSName.RESOURCES);
    if (resourcesDict == null)
        return;
    PDResources resources = new PDResources(resourcesDict);
    Map<String, PDXObject> xObjects = resources.getXObjects();
    if (xObjects == null)
        return;

    for (Map.Entry<String, PDXObject> entry : xObjects.entrySet())
    {
        PDXObject xObject = entry.getValue();
        String xObjectFormat = String.format(patternFormat, "-" + entry.getKey() + "%s", "%s");
        if (xObject instanceof PDXObjectForm)
            extractPatternImages((PDXObjectForm)xObject, xObjectFormat);
        else if (xObject instanceof PDXObjectImage)
            extractPatternImages((PDXObjectImage)xObject, xObjectFormat);
    }
}
 
Example 32
Project: Pdf2Dom   File: PDFBoxTree.java   Source Code and License 6 votes vote down vote up
private void processFontResources(PDResources resources, FontTable table) throws IOException
{
    String fontNotSupportedMessage = "Font: {} skipped because type '{}' is not supported.";

    for (COSName key : resources.getFontNames())
    {
        PDFont font = resources.getFont(key);
        if (font instanceof PDTrueTypeFont)
        {
            table.addEntry( font);
            log.debug("Font: " + font.getName() + " TTF");
        }
        else if (font instanceof PDType0Font)
        {
            PDCIDFont descendantFont = ((PDType0Font) font).getDescendantFont();
            if (descendantFont instanceof PDCIDFontType2)
                table.addEntry(font);
            else
                log.warn(fontNotSupportedMessage, font.getName(), font.getClass().getSimpleName());
        }
        else if (font instanceof PDType1CFont)
            table.addEntry(font);
        else
            log.warn(fontNotSupportedMessage, font.getName(), font.getClass().getSimpleName());
    }

    for (COSName name : resources.getXObjectNames())
    {
        PDXObject xobject = resources.getXObject(name);
        if (xobject instanceof PDFormXObject)
        {
            PDFormXObject xObjectForm = (PDFormXObject) xobject;
            PDResources formResources = xObjectForm.getResources();
            if (formResources != null)
                processFontResources(formResources, table);
        }
    }

}
 
Example 33
Project: Pdf2Dom   File: PDFBoxTree.java   Source Code and License 6 votes vote down vote up
protected void processImageOperation(List<COSBase> arguments) throws IOException
{
    COSName objectName = (COSName)arguments.get( 0 );
    PDXObject xobject = getResources().getXObject( objectName );
    if (xobject instanceof PDImageXObject)
    {
        PDImageXObject pdfImage = (PDImageXObject) xobject;
        BufferedImage outputImage = pdfImage.getImage();
        outputImage = rotateImage(outputImage);

        ImageResource imageData = new ImageResource(getTitle(), outputImage);

        Rectangle2D bounds = calculateImagePosition(pdfImage);
        float x = (float) bounds.getX();
        float y = (float) bounds.getY();

        renderImage(x, y, (float) bounds.getWidth(), (float) bounds.getHeight(), imageData);
    }
}
 
Example 34
Project: jabref   File: PdfAnnotationImporter.java   Source Code and License 6 votes vote down vote up
private FileAnnotation createMarkedAnnotations(int pageIndex, PDPage page, PDAnnotation annotation) {
    FileAnnotation annotationBelongingToMarking = new FileAnnotation(
            annotation.getDictionary().getString(COSName.T), FileAnnotation.extractModifiedTime(annotation.getModifiedDate()),
            pageIndex + 1, annotation.getContents(), FileAnnotationType.valueOf(annotation.getSubtype().toUpperCase(Locale.ROOT)), Optional.empty());

    if (annotationBelongingToMarking.getAnnotationType().isLinkedFileAnnotationType()) {
        try {
            COSArray boundingBoxes = (COSArray) annotation.getDictionary().getDictionaryObject(COSName.getPDFName("QuadPoints"));
            annotation.setContents(new TextExtractor(page, boundingBoxes).extractMarkedText());
        } catch (IOException e) {
            annotation.setContents("JabRef: Could not extract any marked text!");
        }
    }

    //Marked text that has a sticky note on it should be linked to the sticky note
    return new FileAnnotation(annotation, pageIndex + 1, annotationBelongingToMarking);
}
 
Example 35
Project: ph-pdf-layout   File: PDPageContentStreamExt.java   Source Code and License 6 votes vote down vote up
private COSName getName (final PDColorSpace colorSpace)
{
  if (colorSpace instanceof PDDeviceGray || colorSpace instanceof PDDeviceRGB || colorSpace instanceof PDDeviceCMYK)
  {
    return COSName.getPDFName (colorSpace.getName ());
  }
  return resources.add (colorSpace);
}
 
Example 36
Project: Harmonia-1.5   File: PDFFormUIBuilder.java   Source Code and License 6 votes vote down vote up
/**
 * Locates the PDField's found on a given page as an Iterable.
 * 
 * @param pageNum
 *            - the page number to get the fields of.
 * @return a list of PDField's on that page.
 */
private Iterable<PDField> getIterableFieldsForPage(int pageNum) {
	PDAcroForm acroForm = _doc.getDocumentCatalog().getAcroForm();
	try {
		/*
		 * What this line states is: From all the fields of the form
		 * (acroForm.getFields()) return only the fields whose that satisfy
		 * the second argument. The second argument joins a function that
		 * finds the page number that a field is set on, with a predicate
		 * that compares that number with the number we are looking for
		 * (pageNum).
		 * 
		 * Read aloud it says From all fields, return only those fields that
		 * are attached to the given page number.
		 */
		return filter(
				acroForm.getFields(),
				compose(withPageNumber(pageNum),
						getFirstParentOfType(COSName.PAGE, PDPage.class)));
	} catch (IOException e) {
		e.printStackTrace(); // To change body of catch statement use File |
								// Settings | File Templates.
	}
	return Lists.newArrayList();
}
 
Example 37
Project: pdfbox-graphics2d   File: PdfBoxGraphics2D.java   Source Code and License 5 votes vote down vote up
private void applyShadingAsColor(PDShading shading) throws IOException {
	/*
	 * If the paint has a shading we must create a tiling pattern and set
	 * that as stroke color...
	 */
	PDTilingPattern pattern = new PDTilingPattern();
	pattern.setPaintType(PDTilingPattern.PAINT_COLORED);
	pattern.setTilingType(PDTilingPattern.TILING_CONSTANT_SPACING_FASTER_TILING);
	PDRectangle anchorRect = bbox;
	pattern.setBBox(anchorRect);
	pattern.setXStep(anchorRect.getWidth());
	pattern.setYStep(anchorRect.getHeight());

	PDAppearanceStream appearance = new PDAppearanceStream(this.document);
	appearance.setResources(pattern.getResources());
	appearance.setBBox(pattern.getBBox());

	PDPageContentStream imageContentStream = new PDPageContentStream(document, appearance,
			((COSStream) pattern.getCOSObject()).createOutputStream());
	imageContentStream.addRect(0, 0, anchorRect.getWidth(), anchorRect.getHeight());
	imageContentStream.clip();
	imageContentStream.shadingFill(shading);
	imageContentStream.close();

	PDColorSpace patternCS1 = new PDPattern(null);
	COSName tilingPatternName = xFormObject.getResources().add(pattern);
	PDColor patternColor = new PDColor(tilingPatternName, patternCS1);

	contentStream.setNonStrokingColor(patternColor);
	contentStream.setStrokingColor(patternColor);
}
 
Example 38
Project: peten   File: GreyscaleLosslessFactory.java   Source Code and License 5 votes vote down vote up
/**
 * Create a PDImageXObject while making a decision whether not to 
 * compress, use Flate filter only, or Flate and LZW filters.
 * 
 * @param document The document.
 * @param byteArray array with data.
 * @param width the image width
 * @param height the image height
 * @param bitsPerComponent the bits per component
 * @param initColorSpace the color space
 * @return the newly created PDImageXObject with the data compressed.
 * @throws IOException 
 */
private static PDImageXObject prepareImageXObject(PDDocument document, 
        byte [] byteArray, int width, int height, int bitsPerComponent, 
        PDColorSpace initColorSpace) throws IOException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Filter filter = FilterFactory.INSTANCE.getFilter(COSName.FLATE_DECODE);
    filter.encode(new ByteArrayInputStream(byteArray), baos, new COSDictionary(), 0);

    ByteArrayInputStream encodedByteStream = new ByteArrayInputStream(baos.toByteArray());
    return new PDImageXObject(document, encodedByteStream, COSName.FLATE_DECODE, 
            width, height, bitsPerComponent, initColorSpace);
}
 
Example 39
Project: kumoreg   File: StaffBadge2017.java   Source Code and License 5 votes vote down vote up
void addBadge(Attendee attendee, Integer xOffset, Integer yOffset) throws IOException {
    PDPage templatePage = frontBackground.getDocumentCatalog().getPages().get(0);
    COSDictionary pageDict = templatePage.getCOSObject();
    COSDictionary newPageDict = new COSDictionary(pageDict);
    newPageDict.removeItem(COSName.ANNOTS);
    newPageDict.removeItem(COSName.ACTUAL_TEXT);

    PDPage page = document.importPage(new PDPage(newPageDict));

    // Positions are measured from the bottom left corner of the page at 72 DPI
    drawDepartmentBackgroundColorFront(page, attendee);
    //drawDepartmentNameFront(page, attendee);
    drawPositionsFront(page, attendee);
    drawImage(page, attendee);
    drawName(page, attendee);
    drawAgeImageFront(page, attendee);

    // Badge back
    PDPage templateBack = backBackground.getDocumentCatalog().getPages().get(0);
    COSDictionary backPageDict = templateBack.getCOSObject();
    COSDictionary newBackPageDict = new COSDictionary(backPageDict);
    newBackPageDict.removeItem(COSName.ANNOTS);
    newBackPageDict.removeItem(COSName.ACTUAL_TEXT);

    PDPage pageBack = document.importPage(new PDPage(newBackPageDict));
    drawDepartmentBackgroundColorBack(pageBack, attendee);
    //drawDepartmentNameBack(pageBack, attendee);
    drawPositionsBack(pageBack, attendee);
    drawNameBack(pageBack, attendee);
    drawAgeImageBack(pageBack, attendee);
}
 
Example 40
Project: pdf-box-examples   File: ImageExtractor.java   Source Code and License 5 votes vote down vote up
/**
 * This is used to handle an operation.
 *
 * @param operator The operation to perform.
 * @param operands The list of arguments.
 * @throws IOException If there is an error processing the operation.
 */
@Override
protected void processOperator(Operator operator, List<COSBase> operands) throws IOException {
    String operation = operator.getName();
    if (INVOKE_OPERATOR.equals(operation)) {
        COSName objectName = (COSName) operands.get(0);
        PDXObject xobject = getResources().getXObject(objectName);
        if (xobject instanceof PDImageXObject) {

            PDImageXObject image = (PDImageXObject) xobject;
            Matrix ctmNew = getGraphicsState().getCurrentTransformationMatrix();

            Image im = new Image();
            im.setPage(currentPage);
            im.setXPosition(ctmNew.getTranslateX());
            im.setYPosition(ctmNew.getTranslateY());
            im.setOriginalHeight(image.getHeight());
            im.setOriginalWidth(image.getWidth());
            im.setRenderedWidth(Math.round(ctmNew.getScaleX()));
            im.setRenderedHeight(Math.round(ctmNew.getScaleY()));
            images.add(im);

            if (!output.exists()) output.mkdirs();
            // TODO enable option to set the output format. right now it uses original which means: tiff needs extra dependency and tiff are HUGE!
            // String extension = "png";
            String extension = image.getSuffix();
            File out = new File(output, basename + "-" + currentPage + "-" + count + "." + extension);

            ImageIO.write(image.getImage(), extension, new FileOutputStream(out));
            count++;

        } else if (xobject instanceof PDFormXObject) {
            PDFormXObject form = (PDFormXObject) xobject;
            showForm(form);
        }
    } else {
        super.processOperator(operator, operands);
    }
}