我可以在现有的pdf中添加文本,如下面的网址所述。 但是当我添加文本时,文本会保留在pdf中的图像下方。我该如何解决这个问题?
ITextSharp insert text to an existing pdf
编辑:
public void createFromPDF(string mapPath)
{
string oldFile = mapPath.Replace("Home", "") + "Content\\Uploads\\fiyat-listesi.pdf";// "oldFile.pdf";
string newFile = mapPath.Replace("Home", "") + "Content\\Uploads\\new.pdf";//"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(Color.RED);
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);
document.NewPage();
Paragraph p = new Paragraph("aaaaaaaaaaaaaaaaaa", new Font(bf));
document.Add(p);
PdfImportedPage page2 = writer.GetImportedPage(reader, 2);
cb.AddTemplate(page2, 0, 0);
document.NewPage();
Paragraph pwe = new Paragraph("aaaaaaaaaaaaaaaaaa", new Font(bf));
document.Add(p);
cb.EndLayer();
PdfImportedPage page3 = writer.GetImportedPage(reader, 3);
cb.AddTemplate(page3, 0, 0);
// close the streams and voilá the file should be changed :)
document.Close();
fs.Close();
writer.Close();
reader.Close();
}
答案 0 :(得分:2)
两个评论:
PdfImportedPage
和PdfWriter
来操纵现有PDF。这证明你没有阅读文档。您应该使用PdfStamper
代替!您的代码太复杂了。切换到PdfStamper
并使用ColumnText
对象添加文本。不要使用BeginText()
/ EndText()
。另外:你为什么使用EndLayer()
???你知道那个方法意味着什么吗?