I suppose what you want is the PdfWriter to auto-scale the Image inside the Document.
Optionally, position the Image in the center of the Page.
您可以更改代码设置[Image].SetAutoScale(true)
和[Image].SetHorizontalAlignment(HorizontalAlignment.CENTER)
:
Note:我为iText.Layout.Properties
(别名:PdfProperties
)和iText.Layout.Element.Image
(别名:PdfImage
)定义了别名,以避免与其他别名冲突.Net程序集,这些程序集的类和枚举数具有相同的确切名称.只要把它们取下来,以防你根本不需要它们.
using iText.IO.Image;
using iText.Kernel.Pdf;
using iText.Layout;
using PdfProperties = iText.Layout.Properties;
using PdfImage = iText.Layout.Element.Image;
public byte[] ConvertImageToPDF(byte[] imageBytes)
{
using (var ms = new MemoryStream()) {
using (var pdfWriter = new PdfWriter(ms)) {
var pdf = new PdfDocument(pdfWriter);
var document = new Document(pdf);
var img = new PdfImage(ImageDataFactory.Create(imageBytes))
.SetAutoScale(true)
.SetHorizontalAlignment(PdfProperties.HorizontalAlignment.CENTER);
document.Add(img);
document.Close();
pdf.Close();
return ms.ToArray();
}
}
}
You can also specify the size, in floating point units, of the Image and use the [Image].ScaleToFit()
method, to scale the Image within those bounds.
Here, using a PageSize
set to PageSize.A4
. You can of course set different measures.
using iText.Kernel.Geom;
// [...]
var document = new Document(pdf);
var page = document.GetPageEffectiveArea(PageSize.A4);
var img = new PdfImage(ImageDataFactory.Create(imageBytes))
.ScaleToFit(page.GetWidth(), page.GetHeight())
.SetHorizontalAlignment(PdfProperties.HorizontalAlignment.CENTER);
// [...]