有人知道为什么我的标题或边距无法在页面上工作/生成吗?它只生成带有“hello脖子”段落的pdf
import java.awt.Desktop;
import java.io.FileOutputStream;
import java.io.OutputStream;
import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.*;
public class Report {
public static void main(String arg[])throws Exception
{
try{
File temp = File.createTempFile("tempfile", ".pdf");
OutputStream file = new FileOutputStream(temp);
Document document = new Document();
PdfWriter.getInstance(document, file);
document.open();
document.addHeader("header1", "this is my header file");
document.setMargins(50, 50, 100, 100);
document.add(new Paragraph("hello neck"));
document.close();
file.close();
if (Desktop.isDesktopSupported()) {
Desktop dtop = Desktop.getDesktop();
if (dtop.isSupported(Desktop.Action.OPEN)) {
String temp2 = temp.getPath();
dtop.open(new File(temp2));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
最佳答案
标题类型错误。这是元信息,而不是页眉和页脚。
考虑“内容类型”而不是“第 x 页,共 y 页”。
//these two lines of code are identical
document.addHeader("a", "b");
document.add(new Header("a", "b"));
Header
继承自 Meta
,它处理作者/标题/等/等。 header 适用于不属于标准值之一的任意字符串。
此外,您只能在调用 document.open() 之前更改元数据。之后,任何更改都会被忽略(或者它们会抛出......我不记得了)
但是您需要页眉和页脚。传统的处理方法是通过 PdfPageEvent
的 OnEndPage 函数。如果您继承自 PdfPageEventHelper
,它已经删除了 PdfPageEvent
接口(interface)中的所有函数,因此您只需重写您想要的函数即可。方便。
在 OnEndPage 中,您需要使用 ColumnText
对象将文本写入提供的 PdfContentByte。
关于java - java中的pdf文件无法添加页眉或边距?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5716124/