问题
my goal is to move text in a PDF around, which is within a certain rectangular area. There is an existing Item on stackoverflow, which already got me close to achiving this: iText or iTextSharp rudimentary text edit
However, I would be back at manipulating the PDF on a very basic level. Is there a chance to use higher level facilities of itext to alter the position of the text? I'm afraid there is no simple solution, but I'd be happy to get some suggestions.
PS: Also keep in mind that I want to move around only text within a rectangular area, i.e. text(chunks) matching the area in the original PDF should be shifted some in their x and y coordinates. I have no influence on how the PDF are created and I can accept a solution that only vaguely works.
回答1:
I thought I understood your question, but your response to my counter-question is confusing, so let me give you an example that answers your question as I interpret it.
Suppose that you have a text like this:
I also have the coordinates of a rectangle: new Rectangle(100, 500, 200, 600);
and an offset: move everything in that rectangle 10 points to the left and 2 points to the bottom, like this:
That is fairly easy to achieve. Take a look at the CutAndPaste example:
public void manipulatePdf(String src, String dest)
throws IOException, DocumentException {
// Creating a reader
PdfReader reader = new PdfReader(src);
// step 1
Rectangle pageSize = reader.getPageSize(1);
Rectangle toMove = new Rectangle(100, 500, 200, 600);
Document document = new Document(pageSize);
// step 2
PdfWriter writer
= PdfWriter.getInstance(document, new FileOutputStream(dest));
// step 3
document.open();
// step 4
PdfImportedPage page = writer.getImportedPage(reader, 1);
PdfContentByte cb = writer.getDirectContent();
PdfTemplate template1 = cb.createTemplate(pageSize.getWidth(), pageSize.getHeight());
template1.rectangle(0, 0, pageSize.getWidth(), pageSize.getHeight());
template1.rectangle(toMove.getLeft(), toMove.getBottom(),
toMove.getWidth(), toMove.getHeight());
template1.eoClip();
template1.newPath();
template1.addTemplate(page, 0, 0);
PdfTemplate template2 = cb.createTemplate(pageSize.getWidth(), pageSize.getHeight());
template2.rectangle(toMove.getLeft(), toMove.getBottom(),
toMove.getWidth(), toMove.getHeight());
template2.clip();
template2.newPath();
template2.addTemplate(page, 0, 0);
cb.addTemplate(template1, 0, 0);
cb.addTemplate(template2, -20, -2);
// step 4
document.close();
reader.close();
}
If this is not what you want. If you want to detect actual words and move those words, then you have a problem. In that case, we are talking about a project that could easily cost a couple of months of work to do it correctly, and your short question would be largely insufficient to know what to do in the many edge cases that can be imagined.
来源:https://stackoverflow.com/questions/28368317/itext-or-itextsharp-move-text-in-an-existing-pdf