0

am trying to evaluate itext7, so i have an existing pdf and i want to replace some text in it but this is not working, below is my code; i will appreciate some help. Thanks

protected static void manipulatePdf(String src, String dest) throws Exception {
    PdfDocument pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
    PdfPage page = pdfDoc.getFirstPage();
    PdfDictionary dict = page.getPdfObject();
    PdfObject object = dict.get(PdfName.Contents);
    if (object instanceof PdfStream) {
        PdfStream stream = (PdfStream) object;
        byte[] data = stream.getBytes();
        stream.setData(new String(data).replace("Sehr", "Very").getBytes("UTF-8"));
    }
    pdfDoc.close();
}
  • 1. You're doing something that is *sehr schmutzig*. PDF isn't a format for editing, and replacing strings in a content stream will almost always result in ugly PDFs because you're breaking the layout 2. While you may see the word `Sehr` on a page, that word may not be present as such in the content stream. It can be in a Form XObject that is referred to from the content stream. It can be split up in parts and be part of a text array. 3. Bottom line: one simply does not replace a word with another word in PDF. I'll see if I can close this question as a duplicate. – Bruno Lowagie Oct 06 '16 at 12:25
  • I've closed the question as a duplicate. Another question you may want to read is this one: [iText or iTextSharp rudimentary text edit](http://stackoverflow.com/questions/21617218/itext-or-itextsharp-rudimentary-text-edit). Both answers are valid for PDF in general, regardless of whether you're using iText 5 or iText 7. – Bruno Lowagie Oct 06 '16 at 12:30
  • Thanks Bruno, would you rather advise that i generated the pdf document all from scratch programatically than modifying an existing one? – lawrence wamala Oct 06 '16 at 12:42
  • If you have the source (the data and the code, the original Word document, the original text document), then it's always better to recreate the PDF from scratch. That way the layout will be done correctly. In your current setup, replacing a short word with a long word (or vice-versa) will garble your layout (assuming that those words can be found literally in the content stream). – Bruno Lowagie Oct 06 '16 at 13:58

0 Answers0