iTextSharp新增圖片生成PDF檔案
阿新 • • 發佈:2019-02-17
public void iTextSharpCreatPDF() { string pdfpath = System.Web.HttpContext.Current.Server.MapPath("~/log/DPD/"); 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 + "/DPD_15505984238198.pdf", FileMode.Create)); doc.Open(); //下面對圖片進行操作 Image image = Image.GetInstance(imagepath + "/DPD_15505984238198.jpg"); float percentage = 1; //這裡都是圖片最原始的寬度與高度 float resizedWidht = image.Width; float resizedHeight = image.Height; ////這時判斷圖片寬度是否大於頁面寬度減去也邊距,如果是,那麼縮小,如果還大,繼續縮小, ////這樣這個縮小的百分比percentage會越來越小 //while (resizedWidht > (doc.PageSize.Width - doc.LeftMargin - doc.RightMargin) * 0.8) //{ // percentage = percentage * 0.9f; // resizedHeight = image.Height * percentage; // resizedWidht = image.Width * percentage; //} ////There is a 0.8 here. If the height of the image is too close to the page size height, ////the image will seem so big //while (resizedHeight > (doc.PageSize.Height - doc.TopMargin - doc.BottomMargin) * 0.8) //{ // percentage = percentage * 0.9f; // resizedHeight = image.Height * percentage; // resizedWidht = image.Width * percentage; //} ////這裡用計算出來的百分比來縮小圖片 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(); } }