Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert a thumbnail for PDF attachment using apache PDF-Box

I have a code to attach a file to a PDF file.

PDDocument doc = new PDDocument();
PDPage page = new PDPage();
doc.addPage(page);

// read attachment file
File file = new File("/Users/TMac/Projects/Web/dir/index.html");
FileInputStream inputStream = new FileInputStream(file);

PDEmbeddedFile pdEmbeddedFile = new PDEmbeddedFile(doc, inputStream );
pdEmbeddedFile.setSubtype( "application/octet-stream" );

PDComplexFileSpecification fs = new PDComplexFileSpecification();
fs.setEmbeddedFile( pdEmbeddedFile );
fs.setFile("index.html");

int offsetX = 20;
int offsetY = 600;

PDAnnotationFileAttachment txtLink = new PDAnnotationFileAttachment();
txtLink.setFile(fs);

// Set the rectangle containing the link
PDRectangle position = new PDRectangle();
position.setLowerLeftX(offsetX);
position.setLowerLeftY(offsetY);
position.setUpperRightX(offsetX + 20);
position.setUpperRightY(offsetY + 20);
txtLink.setRectangle(position);

page.getAnnotations().add(txtLink);

doc.save("/Users/TMac/Projects/PDF/outputFiles/testHTML.pdf");
doc.close();

The problem is the attachment icon is looks like this:

enter image description here

I need to replace this icon with custom image.I have found some examples related to text links. when i click on that image it should open the file. Attachment code (above code) working fine. How can i add a custom image as a thumbnail ?

like image 497
Nuwan Chamara Avatar asked Dec 08 '25 21:12

Nuwan Chamara


1 Answers

You need to create an appearance stream:

PDAnnotationFileAttachment txtLink = new PDAnnotationFileAttachment();
txtLink.setFile(fs);
// Set the rectangle containing the link
int offsetX = 20;
int offsetY = 600;
PDRectangle position = new PDRectangle();
position.setLowerLeftX(offsetX);
position.setLowerLeftY(offsetY);
position.setUpperRightX(offsetX + 20);
position.setUpperRightY(offsetY + 20);
txtLink.setRectangle(position);

PDAppearanceDictionary appearanceDictionary = new PDAppearanceDictionary();
PDAppearanceStream appearanceStream = new PDAppearanceStream(doc);
appearanceStream.setResources(new PDResources());
PDRectangle bbox = new PDRectangle(txtLink.getRectangle().getWidth(), txtLink.getRectangle().getHeight());
appearanceStream.setBBox(bbox);
try (PDPageContentStream cs = new PDPageContentStream(doc, appearanceStream))
{
    PDImageXObject image = PDImageXObject.createFromFile("image.jpg", doc);
    cs.drawImage(image, 0, 0);
}
appearanceDictionary.setNormalAppearance(appearanceStream);
txtLink.setAppearance(appearanceDictionary);

page.getAnnotations().add(txtLink);
like image 110
Tilman Hausherr Avatar answered Dec 11 '25 10:12

Tilman Hausherr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!