Itext 7 library replaces text in pdf file, but the selected text is not in the right position

30 views Asked by At

I'm using the itext 7 library in a java project. In input I have a pdf file in which I cover some words with a white background and replace them with other words, and I insert the result into a new pdf file. Everything works fine, the new pdf has the words I wanted replaced, but if I select all the text and copy it to a notepad, the words I inserted are inserted at the end of each page and not in the correct positions. This is a piece of my code:

PdfReader reader = new PdfReader(src);
PdfWriter writer = new PdfWriter(dest);
PdfDocument pdfDocument = new PdfDocument(reader, writer);

// First step: cleaning entities occurrences
for (ITextArea area : areas) {
    cleanAreaContent(pdfDocument, area);
}

// Second step: adding pseudonym text
for (ITextArea area : areas) {
    Rectangle rect = (Rectangle) area;
    PdfPage page = pdfDocument.getPage(area.getPageNumber() + 1);

    PdfFont font = PdfFontFactory.createFont(StandardFonts.TIMES_ITALIC);
    float height = rect.getHeight();
    float width = rect.getWidth();

    Text pseudonym = new Text(area.getPseudonym());
    pseudonym.setFont(font);
    PdfCanvas pdfCanvas = new PdfCanvas(page);
    try (Canvas canvas = new Canvas(pdfCanvas, rect)) {
      Paragraph paragraph = new Paragraph(pseudonym).setFont(font).setHorizontalAlignment(HorizontalAlignment.CENTER).setVerticalAlignment(VerticalAlignment.MIDDLE);
      canvas.add(paragraph);
      canvas.setProperty(Property.APPEARANCE_STREAM_LAYOUT, false);
      canvas.showTextAligned(paragraph, width / 2, height / 2,TextAlignment.CENTER, VerticalAlignment.MIDDLE);      }
  }
  pdfDocument.close();
}

Searching online for PDF files produced like this, I noticed that they all have the same problem, so my question is whether it could be a problem with the Itext library? Thank you.

0

There are 0 answers