使用iTextSharp将图像添加到PDF并正确缩放

这是我的代码。 它正确添加了我想要的图片, 除了图像使用原始分辨率 ,一切正常,因此如果图像很大,则会裁剪它以适应页面。

有没有办法让图片像缩放function一样使用拉伸以适应,还能保持宽高比? 我必须在那里找到一些东西。 :P

这是一张图片来说明问题: 替代文字

using System; using System.IO; using iTextSharp.text; using iTextSharp.text.pdf; using System.Drawing; using System.Collections.Generic; namespace WinformsPlayground { public class PDFWrapper { public void CreatePDF(List images) { if (images.Count >= 1) { Document document = new Document(PageSize.LETTER); try { // step 2: // we create a writer that listens to the document // and directs a PDF-stream to a file PdfWriter.GetInstance(document, new FileStream("Chap0101.pdf", FileMode.Create)); // step 3: we open the document document.Open(); foreach (var image in images) { iTextSharp.text.Image pic = iTextSharp.text.Image.GetInstance(image, System.Drawing.Imaging.ImageFormat.Jpeg); document.Add(pic); document.NewPage(); } } catch (DocumentException de) { Console.Error.WriteLine(de.Message); } catch (IOException ioe) { Console.Error.WriteLine(ioe.Message); } // step 5: we close the document document.Close(); } } } } 

我使用以下方法解决了它:

 foreach (var image in images) { iTextSharp.text.Image pic = iTextSharp.text.Image.GetInstance(image, System.Drawing.Imaging.ImageFormat.Jpeg); if (pic.Height > pic.Width) { //Maximum height is 800 pixels. float percentage = 0.0f; percentage = 700 / pic.Height; pic.ScalePercent(percentage * 100); } else { //Maximum width is 600 pixels. float percentage = 0.0f; percentage = 540 / pic.Width; pic.ScalePercent(percentage * 100); } pic.Border = iTextSharp.text.Rectangle.BOX; pic.BorderColor = iTextSharp.text.BaseColor.BLACK; pic.BorderWidth = 3f; document.Add(pic); document.NewPage(); } 

你可以尝试这样的事情:

  Image logo = Image.GetInstance("pathToTheImage") logo.ScaleAbsolute(500, 300) 

就个人而言,我使用了与fubo解决方案关系密切的东西,效果很好:

 image.ScaleToFit(document.PageSize); image.SetAbsolutePosition(0,0); 
 image.ScaleToFit(500f,30f); 

此方法保持图像的纵横比

 image.SetAbsolutePosition(1,1);