mardi 7 février 2017

Turning a set of PDFBox Annotations into Images

Vote count: 0

I have a program that generates PDF files, and uses the annotation feature to easily draw shapes dynamically, but I'm finding that many users have trouble seeing, and especially printing the annotations due to the way some PDF viewers treat them.

I can turn the pages themselves to images, but all of the annotations vanish when I do it. I tried using the answer from

Using PDFBox, how to set an appearance stream on annotation?

But several of the methods seem to be deprecated or changed entirely, and my attempts to replace them lead to errors.

Here is what I have so far:

 public void annotToImage() throws IOException {

    PDDocument doc = new PDDocument();
    PDPage p = new PDPage();
    doc.addPage(p);
    List<PDAnnotation> ann = p.getAnnotations();


    PDAnnotationSquareCircle square = new PDAnnotationSquareCircle(PDAnnotationSquareCircle.SUB_TYPE_SQUARE);
    PDRectangle position = new PDRectangle();
    position.setLowerLeftX(100);
    position.setLowerLeftY(100);
    position.setUpperRightX(200);
    position.setUpperRightY(200);
    square.setRectangle(position);
    square.setInteriorColor(Part_Type.CDS.getColor());


    PDResources holderFormResources = new PDResources();
    PDStream holderFormStream = new PDStream(doc);
    PDFormXObject holderForm = new PDFormXObject(holderFormStream);
    holderForm.setResources(holderFormResources);
    holderForm.setBBox(position);
    holderForm.setFormType(1);

    PDAppearanceDictionary appearance = new PDAppearanceDictionary();
    appearance.getCOSObject().setDirect(true);
    PDAppearanceStream appearanceStream = new PDAppearanceStream(holderForm.getCOSObject());
    holderForm.getCOSStream().createFilteredStream();
    appearance.setNormalAppearance(appearanceStream);

    square.setAppearance(appearance);



    ann.add(square);

    PDFRenderer render = new PDFRenderer(doc);


    BufferedImage b = render.renderImageWithDPI(0, 300, ImageType.RGB);

    ImageIOUtil.writeImage(b, "/my/path/here.png", 300);
    doc.close();

This generates:

java.lang.IllegalStateException: Cannot read while there is an open stream writer

at

BufferedImage b = render.renderImageWithDPI(0, 300, ImageType.RGB);

Attempts to manually close various streams have just lead to errors telling me that the document has been closed. I'm not sure if I'm doing this correctly, and additionally how to modify the method to apply to a series of annotations instead of just one.

asked 15 secs ago

Let's block ads! (Why?)



Turning a set of PDFBox Annotations into Images

Aucun commentaire:

Enregistrer un commentaire