更新时间:2022-06-24 08:29:19
这是完全错误的:
reader = new PdfReader(fileOut);
Document final = new Document(reader.GetPageSize(1));
PdfWriter w = PdfWriter.GetInstance(final, new FileStream(finalFile, FileMode.Create, FileAccess.Write));
w.SetFullCompression();
final.Open();
for (int i = 1; i <= reader.NumberOfPages; i++)
{
final.NewPage();
PdfContentByte cb = w.DirectContent;
ControlNumberTimes(cb, "C"+i, 560, 725, 270, Element.ALIGN_LEFT);
cb.AddTemplate(w.GetImportedPage(reader, i), 0, 0);
}
final.Close();
说我正在使用文件复制文件
, PdfWriter
, PdfImportedPage
和 AddTemplate
,为什么我的文件大小增加?就像问我用锋利的刀刺伤自己的肚子,我为什么要流血?
Saying "I am copying a file using Document
, PdfWriter
, PdfImportedPage
and AddTemplate
, why does my file size increase?" is like asking "I've stabbed myself in the belly with a sharp knife, why do I bleed?"
如果你想在现有文件中添加页码,您必须按 PdfStamper 9b03-3f9aca1921a5 / samplechapter6.pdfrel =nofollow>我书中的第6章。
If you want to add page numbers to an existing document, you have to use PdfStamper
as explained in chapter 6 of my book.
你想操纵现有PDF ,更具体地说,您希望在页脚中添加页码。这是这样做的:
You want to manipulate an existing PDF, more specifically, you want to add page numbers in the footer. That is done like this:
PdfReader reader = new PdfReader(outputFile);
using (FileStream fs = new FileStream(secondFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
using (PdfStamper stamper = new PdfStamper(reader, fs)) {
int PageCount = reader.NumberOfPages;
for (int i = 1; i <= PageCount; i++) {
ColumnText.ShowTextAligned(stamper.GetOverContent(i), Element.ALIGN_CENTER, new Phrase(String.Format("Page {0} of {1}", i, PageCount)), 560, 725, 270);
}
}
}
一些评论:
BeginText()
... EndText()
,但是你可能更容易使用 ColumnText.ShowTextAligned()
。 BaseFont
时嵌入,如此 BaseFont.CreateFont(C:\\windows \\Fonts \\ times。 ttf,BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED)
。这不是真的。如上所述,使用 BaseFont.IDENTITY_H
时,将忽略 BaseFont.NOT_EMBEDDED
。请参阅为什么iText嵌入字体即使我指定不嵌入?如果需要小文件大小,我建议你不要嵌入字体。BeginText()
... EndText()
, but it might be easier for you to use ColumnText.ShowTextAligned()
.BaseFont
like this BaseFont.CreateFont("C:\\windows\\Fonts\\times.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED)
. That's not true. As documented, BaseFont.NOT_EMBEDDED
is ignored when using BaseFont.IDENTITY_H
. See Why is iText embedding a font even when I specify not to embed? If a small file size is desired, I suggest you don't embed the font.您的代码的主要问题是您没有以正确的方式操作文件。我认为这是因为您从一个写得不好的教程中复制/粘贴了您的代码。请不要复制那些不知道他们正在做什么的人的代码。
The main problem with your code, is the fact that you aren't manipulating a file the correct way. I think this is caused by the fact that you copy/pasted your code from a badly written tutorial. Please don't copy code from people who don't know what they're doing.