scaletofit net img getinstance c# image itextsharp

c# - net - Agregar una imagen a un PDF utilizando iTextSharp y escalarla correctamente



itextsharp text image getinstance() (5)

Aquí está mi código. Agrega correctamente las imágenes que quiero y todo funciona, excepto que las imágenes están usando su resolución nativa, por lo que si la imagen es grande, se recorta para que se ajuste a la página.

¿Hay alguna forma de hacer que la imagen se utilice como una función de zoom para ampliarla, pero también mantener la relación de aspecto? Tiene que haber algo que me falta. :PAG

Aquí hay una foto para ilustrar el problema:

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(); } } } }


Lo resolví usando lo siguiente:

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(); }


Personalmente, uso algo cercano a la solución de fubo y funciona bien:

image.ScaleToFit(document.PageSize); image.SetAbsolutePosition(0,0);


Puedes probar algo como esto:

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


image.ScaleToFit(500f,30f);

Este método mantiene la relación de aspecto de la imagen.


image.SetAbsolutePosition(1,1);