Using PDFBox, how to set an appearance stream on a

2019-07-27 02:29发布

I am trying to highlight some text and convert it to image. I tried some stuff but the annotation did not came out on the image. Looking for help found this issue http://issues.apache.org/jira/browse/PDFBOX-2162 which said that I must set appearance-stream to the annotation, something that acrobat reader do it automatically, but when converting to image it is needed. I could not figure out how to set the appearance-stream to the annotation. looked for some examples on annotations and appearance-stream (which I could not find an example that do both.. :-( )

This is what I have so far:

PDDocument document = PDDocument.load("sometest.pdf");
List<PDPage> pages = document.getDocumentCatalog().getAllPages();
PDPage page = pages.get(0);
List<PDAnnotation> annotations = page.getAnnotations();
PDAnnotationTextMarkup annotation = new PDAnnotationTextMarkup(PDAnnotationTextMarkup.SUB_TYPE_HIGHLIGHT);

final PDRectangle boundingBox = new PDRectangle();
//here I set the boundingbox coordinates
annotation.setRectangle(boundingBox);

final float[] quads = this.getQuads(boundingBox);
annotation.setQuadPoints(quads);
annotation.setContents("bla bla");
annotation.setConstantOpacity((float) 0.9);
PDGamma c = new PDGamma();
//Here I set the RGB
annotation.setColour(c);
annotation.setPrinted(true);
//create the Form for the appearance stream
PDResources holderFormResources = new PDResources();
PDStream holderFormStream = new PDStream(document);
PDXObjectForm holderForm = new PDXObjectForm(holderFormStream);
holderForm.setResources(holderFormResources);
holderForm.setBBox(boundingBox);
holderForm.setFormType(1);
// trying to set the appreanceStream for the annotation
PDAppearanceDictionary appearance = new PDAppearanceDictionary();
appearance.getCOSObject().setDirect(true);
PDAppearanceStream appearanceStream = new PDAppearanceStream(holderForm.getCOSStream());
holderForm.getCOSStream().createFilteredStream();
appearance.setNormalAppearance(appearanceStream);

annotation.setAppearance(appearance);

annotations.add(annotation);
//convert to image
BufferedImage image = page.convertToImage(BufferedImage.TYPE_INT_BGR, 600);
ImageIO.write(image, "jpg", new File("test.jpg"));
document.save("test.pdf");
document.close();

The "test.pdf" come out with the annotation, but the image not.

What am I missing?

0条回答
登录 后发表回答