如何使用带C#的ASP.NET将徽标/图像添加到现有的PDF文件中? [英] How to add a logo/image to a existing PDF file using ASP.NET with C#?
本文介绍了如何使用带C#的ASP.NET将徽标/图像添加到现有的PDF文件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用带有c#的asp.net动态地将代码添加到现有PDF文件中的徽标/图像。
尝试下面的代码徽标时添加了作为新的pdf文件。我想添加到现有的pdf文件
我尝试过:
I want to add a logo/image dynamically code wise to an existing PDF file using asp.net with c#.
On trying below code logo is added but as a new pdf file. I want to add to the existing pdf file
What I have tried:
private void AddLogo()
{
string pdfpath = Server.MapPath(".") + "/pdf/test.pdf";
string imagepath = Server.MapPath(".") + "/logo/test.jpg";
Document doc = new Document();
try
{
PdfWriter.GetInstance(doc, new FileStream(pdfpath, FileMode.Create));
doc.Open();
//doc.Add(new Paragraph("GIF"));
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imagepath);
image.ScalePercent(24f);
doc.Add(image);
}
catch (Exception ex)
{
//Log error;
}
finally
{
doc.Close();
}
}
推荐答案
只是一个狂野而疯狂的猜测,但我想你之所以如此创建新文件就是这一行。
Just a wild and crazy guess, but I think the reason why you are always creating new files is this line.
PdfWriter.GetInstance(doc, new FileStream(pdfpath, FileMode.Create));
您正在使用FileMode.Create ...您应该将其更改为FileMode.OpenOrCreate或FileMode.Open。
You are using FileMode.Create...you should probably change that to FileMode.OpenOrCreate or FileMode.Open.
请试试这个
Please try this
using (Stream inputPdfStream = new FileStream(Server.MapPath("~") + "/pdf/test.pdf", FileMode.Open, FileAccess.Read, FileShare.Read))
using (Stream inputImageStream = new FileStream(Server.MapPath("~") + "/logo/test.jpg", FileMode.Open, FileAccess.Read, FileShare.Read))
using (Stream outputPdfStream = new FileStream(Server.MapPath("~") + "/pdf/Result.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
{
var reader = new PdfReader(inputPdfStream);
var stamper = new PdfStamper(reader, outputPdfStream);
var pdfContentByte = stamper.GetOverContent(1);
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(inputImageStream);
image.SetAbsolutePosition(100, 100);
pdfContentByte.AddImage(image);
stamper.Close();
}
这篇关于如何使用带C#的ASP.NET将徽标/图像添加到现有的PDF文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文