上一篇 https://www.cnblogs.com/sun8134/p/18094489 用的 DocNET 可以將 JPG 圖片轉 PDF
但 PNG 圖片會變成空白,如果 PNG 圖片,就需要用 itext-dotnet :https://github.com/itext/itext-dotnet
繼續 Nuget:
Install-Package itext
Install-Package itext.bouncy-castle-adapter
注意:如果不安裝 itext.bouncy-castle-adapter,在 new PdfWriter() 的時候可能會報錯:
Either com.itextpdf:bouncy-castle-adapter or com.itextpdf:bouncy-castle-fips-adapter dependency must be added in order to use BouncyCastleFactoryCreator
合併 PDF:
public static bool Png2Pdf(List<string> imageList, string outputPath) { bool result = false; try { using (FileStream pdfStream = new FileStream(outputPath, FileMode.Create)) { using (PdfWriter pdfWriter = new PdfWriter(pdfStream)) { using (PdfDocument pdfDocument = new PdfDocument(pdfWriter)) { using (Document document = new Document(pdfDocument)) { foreach (string imagePath in imageList) { ImageData imageData = ImageDataFactory.Create(imagePath); iText.Layout.Element.Image img = new iText.Layout.Element.Image(imageData); PdfPage page = pdfDocument.AddNewPage(new iText.Kernel.Geom.PageSize(img.GetImageWidth(), img.GetImageHeight())); document.Add(img); } } } } } result = true; } catch (Exception e) { Console.WriteLine($"error:{e}"); } return result; }
在控制器種調用:
public IActionResult Index() { List<string> imageList = new List<string>(); for (int pageNumber = 1; pageNumber <= 14; pageNumber++) { imageList.Add($"F:\\pdf\\images\\Page_{pageNumber}.png"); } bool result = PdfHelper.Png2Pdf(imageList, "F:\\pdf\\compressed.tracemonkey-pldi-14.pdf"); return Content(result.ToString()); }
看下對比效果:
左邊是jpg右邊是png