Timo
Timo

Reputation: 21

Add Images as Icons to PDF Document using PDFBox

I'm trying to mimic the behavior of the Acrobat JS call doc.importIcon() using PDF Box to import an larger number of images as icons into a PDF document.

I've already created and added an PDAppearanceStream to the AP Dictionary. Unfortunately the Icon is not accessible through doc.getIcon() JS call later in the PDF JS.

Maybe someone of you had the same problem. I guess I'm missing just a small piece here.

My current code looks like this:

PDDocumentCatalog docCatalog = document.getDocumentCatalog();
PDDocumentNameDictionary nameDict = docCatalog.getNames();


COSDictionary dic = nameDict.getCOSObject().getCOSDictionary(COSName.AP);
COSArray names = (COSArray) dic.getDictionaryObject(COSName.NAMES);

PDImageXObject imgNeu = PDImageXObject.createFromFileByContent(new File("C:\\FancyPicture.jpg"), document);
float width = imgNeu.getWidth();
float height = imgNeu.getHeight();

PDAppearanceStream pdAppearanceStream = new PDAppearanceStream(document);
pdAppearanceStream.setResources(new PDResources());
try (PDPageContentStream pdPageContentStream = new PDPageContentStream(document, pdAppearanceStream))
{
    pdPageContentStream.drawImage(imgNeu, 0, 0, width, height);
}
pdAppearanceStream.setBBox(new PDRectangle(width, height));
pdAppearanceStream.setFormType(1);

COSArray defaultRes = new COSArray();
defaultRes.add(COSName.getPDFName("PDF"));
defaultRes.add(COSName.getPDFName("ImageC"));
pdAppearanceStream.getResources().getCOSObject().setItem(COSName.PROC_SET, defaultRes);

Matrix mat = new Matrix(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f);
pdAppearanceStream.setMatrix(mat.createAffineTransform());

COSDictionary strDic = pdAppearanceStream.getCOSObject();
strDic.setString(COSName.NAME, "FRM");

COSString key = new COSString("img_01");
names.add(key.getCOSObject());
names.add(pdAppearanceStream.getCOSObject());

Upvotes: 0

Views: 168

Answers (1)

Timo
Timo

Reputation: 21

It turns out as if the JS runtime within Acrobat requires the COSString elems encoded as UTF-16 incl. Byte order mark

After proper encoding of the icon names and using COSString(byte[]) everything works as expected.

Upvotes: 2

Related Questions