c# - ITextSharp 将文本插入现有的 pdf

标签 c# asp.net pdf itext pdf-generation

标题总结了一切。

我想使用 iTextSharp 将文本添加到现有的 PDF 文件中,但是我无法在网络上的任何地方找到如何做到这一点...

PS:我不能使用 PDF 表单。

最佳答案

我找到了一种方法(不知道它是否最好,但它有效)

string oldFile = "oldFile.pdf";
string newFile = "newFile.pdf";

// open the reader
PdfReader reader = new PdfReader(oldFile);
Rectangle size = reader.GetPageSizeWithRotation(1);
Document document = new Document(size);

// open the writer
FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.Open();

// the pdf content
PdfContentByte cb = writer.DirectContent;

// select the font properties
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252,BaseFont.NOT_EMBEDDED);
cb.SetColorFill(BaseColor.DARK_GRAY);
cb.SetFontAndSize(bf, 8);

// write the text in the pdf content
cb.BeginText();
string text = "Some random blablablabla...";
// put the alignment and coordinates here
cb.ShowTextAligned(1, text, 520, 640, 0);
cb.EndText();
cb.BeginText();
text = "Other random blabla...";
// put the alignment and coordinates here
cb.ShowTextAligned(2, text, 100, 200, 0);
cb.EndText();

// create the new page and add it to the pdf
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate(page, 0, 0);

// close the streams and voilá the file should be changed :)
document.Close();
fs.Close();
writer.Close();
reader.Close();

我希望这对某人有用 =)(并在此处发布任何错误)

关于c# - ITextSharp 将文本插入现有的 pdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3992617/

相关文章:

asp.net - iFrame 中的 Response.Redirect(),重定向父窗口

java - 如何避免PDF添加内容后签名失效?

pdf - 将 PDF 添加到 AFP 输出

c# - 使用基础和MVVM通信在构造函数处进行C#继承

c# - NEST如何在子文档上查找字段

c# - 如何拖动 DataPoint 并将其移动到 Chart 控件中

java - 如何使用servlet从服务器读取pdf文件?

c# - 为 Entity Framework 代码优先应用程序添加索引的正确方法是什么?

asp.net - Base64字符串压缩

c# - 为 ASP.NET 向导控件添加动态步骤