在将pdf文件复制到另一个文件时添加注释 [英] adding annotations while copying a pdf file to another
问题描述
我正在尝试将注释添加到要复制到新pdf的每个页面中,但无法做到这一点...
I am trying to add annotations to every Page which gets copied to my new pdf but not able to do that...
这是我的代码.
import com.lowagie.text.Document;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.*;
import java.awt.*;
import java.io.FileOutputStream;
public class Annotations {
public static void main(String[] args) {
try {
PdfReader reader = new PdfReader("string-to-pdf.pdf");
Document document = new Document(reader.getPageSizeWithRotation(1));
PdfCopy copy = new PdfCopy(document,
new FileOutputStream("temp.pdf"));
copy.setPdfVersion(PdfWriter.VERSION_1_5);
document.open();
for(int i = 1; i <=reader.getNumberOfPages();i++){
copy.addPage(copy.getImportedPage(reader,i));
copy.addAnnotation(PdfAnnotation.createLink(copy, new Rectangle(200f, 700f, 30455454f, 800f), PdfAnnotation.HIGHLIGHT_TOGGLE, PdfAction.javaScript("app.alert('Hello');\r", copy)));
}
document.newPage();
// page 3
PdfContentByte pcb = new PdfContentByte(copy);
pcb.setColorFill(new Color(0xFF, 0x00, 0x00));
document.close();
} catch (Exception de) {
de.printStackTrace();
}
}
}
正在复制文件,但看不到新文件中的注释.
the files are getting copied but can't see the annotations in the new file.
推荐答案
PdfCopy
用于忠实的页面复制,而不是用于创建;因此,从PdfWriter
继承的修改例程将被禁用,例如
PdfCopy
is for faithful page copying, not for creation; thus, modification routines inherited from PdfWriter
are disabled, e.g.
@Override
public void addAnnotation(PdfAnnotation annot) { }
可以通过页面图章进行专用操作,请参见. createPageStamp
.该方法的JavaDocs包含一些示例用法代码,其中包括一个注释:
Dedicated manipulations are possible, though, by means of page stamps, cf. createPageStamp
. The JavaDocs of that method contain some example usage code including an addition of an annotation:
PdfImportedPage page = copy.getImportedPage(reader, 1);
PdfCopy.PageStamp ps = copy.createPageStamp(page);
ps.addAnnotation(PdfAnnotation.createText(copy, new Rectangle(50, 180, 70, 200), "Hello", "No Thanks", true, "Comment"));
PdfContentByte under = ps.getUnderContent();
under.addImage(img);
PdfContentByte over = ps.getOverContent();
over.beginText();
over.setFontAndSize(bf, 18);
over.setTextMatrix(30, 30);
over.showText("total page " + totalPage);
over.endText();
ps.alterContents();
copy.addPage(page);
但是请注意,像这样应用PageStamp
实际上会操纵原始的PdfReader
.因此,此后,请勿继续使用PdfReader
实例,前提是其内容为原始内容,尤其是带有页码的复制页面很脏.
Beware, though, applying a PageStamp
like this actually manipulates the original PdfReader
. Afterwards, therefore, don't continue using the PdfReader
instance assuming its contents are the original contents, in particular the pagestamped copied pages are dirty.
这篇关于在将pdf文件复制到另一个文件时添加注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!