根据图片的URL生成PDF保存到服务器上(后台C#实现)

2021-04-19 20:27

阅读:486

//需要从nuget上下载iTextSharp.dll和itextsharp.xmlworker.dll

public void iTextSharpCreatPDF(string imagepath,string imageName)//图片路径,图片名字
{
string pdfpath = System.Web.HttpContext.Current.Server.MapPath("~/Files/");//要保存的服务器路径
//string imagepath = System.Web.HttpContext.Current.Server.MapPath("~/log/DPD/");
Document doc = new Document(new Rectangle(390, 400), 0, 0, 0, 0); //new Rectangle(1000,1000)
//指定文件预设开档时的缩放为100%
//PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, doc.PageSize.Height, 1f);
try
{
PdfWriter.GetInstance(doc, new FileStream(pdfpath + "/"+ imageName + ".pdf", FileMode.Create));
doc.Open();

//下面对图片进行操作
//Image image = Image.GetInstance(imagepath + "/DPD_15505984238198.jpg");
Image image = Image.GetInstance(imagepath);
float percentage = 1;
//这里都是图片最原始的宽度与高度
float resizedWidht = image.Width;
float resizedHeight = image.Height;

////这里用计算出来的百分比来缩小图片
image.ScalePercent(percentage * 100);
//让图片的中心点与页面的中心店进行重合
image.SetAbsolutePosition(doc.PageSize.Width / 2 - resizedWidht / 2, doc.PageSize.Height / 2 - resizedHeight / 2);
doc.Add(image);

}
catch (DocumentException dex)
{
System.Web.HttpContext.Current.Response.Write(dex.Message);
}
catch (IOException ioex)
{
System.Web.HttpContext.Current.Response.Write(ioex.Message);
}

catch (Exception ex)
{
System.Web.HttpContext.Current.Response.Write(ex.Message);
}
finally
{
doc.Close();
}
}

上一篇:C#反射的一些经验[转载]

下一篇:c# 锁


评论


亲,登录后才可以留言!