This website uses cookies for visitor traffic analysis. By using the website, you agree with storing the cookies on your computer.More information

Posts tagged: Fun

PDF change metadata

Sometimes it is useful to change PDF Metadata.
The following code snipped is based on Add an image to an existing PDF

HashMap<String, String> hmpInfo = new HashMap<String, String>();
hmpInfo.put("Title", "CV");
hmpInfo.put("Author", "rjahn");

PdfDictionary dictTrailer = pdr.getTrailer();

if (dictTrailer != null && dictTrailer.isDictionary())
{
        PdfObject objInfo = PdfReader.getPdfObject(dictTrailer.get(PdfName.INFO));
       
        if (objInfo != null && objInfo.isDictionary())
        {
                PdfDictionary infoDic = (PdfDictionary)objInfo;
               
                for (Map.Entry<String, String>entry : hmpInfo.entrySet())
                {
                        if (entry.getValue().length() == 0)
                        {
                                infoDic.remove(new PdfName(entry.getKey()));
                        }
                        else
                        {
                                infoDic.put(new PdfName(entry.getKey()),
                                 new PdfString(entry.getValue(), PdfObject.TEXT_UNICODE));
                        }
                }
        }
}

pdr.getCatalog().remove(PdfName.METADATA);

Add an image to an existing PDF

Do you know the problem: You got a PDF document and want to add an image to a single page, but you have no printer/scanner.

Normally jPdf Tweak solves simple PDF problems, but it is not possible to add a simple image to a PDF file :( . It supports watermarks, but it is not supported to set the position or page.

I wrote some lines of code to solve my problem:

PdfReader pdr = new PdfReader("D:\\test.pdf");

PdfStamper pds = new PdfStamper(pdr, new FileOutputStream("D:\\test_image.pdf"));

PdfContentByte pcbPosition;

PdfGState pgsTransparency;

Image img;

for (int i = 1, anz = pdr.getNumberOfPages(); i <= anz; i++)
{
        //only first page
        if (i == 1)
        {
                pcbPosition = pds.getOverContent(i);
   
                pgsTransparency = new PdfGState();
                pgsTransparency.setFillOpacity(100 / 100f);
               
                img = Image.getInstance(FileUtil.getContent("D:\\image.png"));
               
                //x: 0 = left
                //y: 0 = bottom
                img.setAbsolutePosition(500f, 250f);
                //70 is 100%
                img.scalePercent(10);
                img.setRotationDegrees(0);
               
                pcbPosition.saveState();

                pcbPosition.setGState(pgsTransparency);
                pcbPosition.addImage(img);
       
                pcbPosition.restoreState();
        }
}

pds.close();

Use the current iText version or iText 4.2.0 (friendly license).