简体   繁体   English

在Java中使用pdfbox将文本覆盖到以前创建的pdf文档上

[英]Using pdfbox in java to overlay text onto previously created pdf document

I already have several PDF documents that have been created. 我已经创建了几个PDF文档。 What I am attempting to do is by using PDFBox. 我正在尝试使用PDFBox。 I need to put text into several places on these created documents but I do NOT want to modify the text that is within those areas. 我需要将文本放入这些创建的文档中的多个位置,但是我不想修改这些区域中的文本。 For instance, there may be aa section as follows - 例如,可能会有一个以下部分-

NAME: ______________________________ 名称: ______________________________

I will put text into that area, but I need the underline to remain the same length. 我将在该区域中输入文字,但需要下划线保持相同的长度。 I believe the best solution would be to just create a textbox or similar that goes above the area so the line remains the same length. 我相信最好的解决方案是仅在该区域上方创建一个文本框或类似文本框,以使该行保持相同的长度。

In other words, I do not want to edit the text inline so it will remain the same length. 换句话说,我不想内联编辑文本,因此它将保持相同的长度。 I have no code for this as I am just attempting to understand the pdfbox package. 我没有任何代码,因为我只是试图了解pdfbox软件包。 I have been looking for examples online, but most of them just show how to create a document and not how to update a previously document. 我一直在网上寻找示例,但是其中大多数只是显示如何创建文档而不是如何更新以前的文档。 How do I do this? 我该怎么做呢?

I found the answer and wanted to share. 我找到了答案,想分享。

In the pdfbox package there is a class called Overlay. 在pdfbox包中,有一个名为Overlay的类。

    PDDocument pdfDocument = new Overlay();
    PDDocument final = pdfDocument.overlay(PDDocument firstDoc, PDDocument otherDoc);

firstDoc will be overlaid onto otherDoc. firstDoc将覆盖在otherDoc上。 Easy peasy. 十分简单。 I just didn't know where to look. 我只是不知道在哪里看。

In case you need concrete example of use, you can refer to OverlayPDF.java in the PDFBox reposity : 如果需要具体的使用示例,可​​以在PDFBox存储 OverlayPDF.java中参考OverlayPDF.java

Overlay overlayer = new Overlay();
overlayer.setInputFile(inputFile);  //the file to be overlayed

PDDocument result = overlayer.overlay(overlayFile); //This will add overlays to a documents.
result.save(outputFilename);
result.close();
overlayer.close();  //close the input files AFTER saving the resulting file

If I understand you correctly, you want to underline text in an existing pdf document. 如果我对您的理解正确,那么您想在现有pdf文档中加下划线。 You can try to use Java Itext, check this example and see if it helps. 您可以尝试使用Java Itext,检查此示例,看看是否有帮助。

http://tutorials.jenkov.com/java-itext/underline-strikethrough.html http://tutorials.jenkov.com/java-itext/underline-strikethrough.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM