[英]Adding an image to a PDF using iTextSharp and scale it properly
这是我的代码。 它正确地添加了我想要的图片, 除了图像使用其原始分辨率外 ,一切正常,因此如果图像很大,则会裁剪它以适合页面。
有没有办法让图片像缩放功能一样使用拉伸以适应,还能保持宽高比? 我必须在那里找到一些东西。 :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<System.Drawing.Image> 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();
}
就个人而言,我使用了与fubo解决方案非常接近的东西并且效果很好:
image.ScaleToFit(document.PageSize);
image.SetAbsolutePosition(0,0);
你可以尝试这样的事情:
Image logo = Image.GetInstance("pathToTheImage")
logo.ScaleAbsolute(500, 300)
image.ScaleToFit(500f,30f);
此方法保持图像的纵横比
image.SetAbsolutePosition(1,1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.