C# insert images and auto fit in pdf via iTextSharp

Install-Package iTextSharp;
Install-Package System.Drawing.Common;

 

private static void InsertsImagesListToPDF(string pdfFile, List<string> imgsList)
{
    string pdfTitle = "SMOOTHTECH";
    string iconPath = @"../../../Images/logo.png";
    using (FileStream fileStream = new FileStream(pdfFile, FileMode.Create, FileAccess.Write, FileShare.None))
    {
        using (Document doc = new Document(PageSize.A1, 36, 36, 144, 50))
        {
            using (PdfWriter pdfWriter = PdfWriter.GetInstance(doc, fileStream))
            {
                var pdfHeaderFooter = new PdfHeaderFooter(pdfTitle, iconPath);
                pdfWriter.PageEvent=pdfHeaderFooter;
                doc.Open();

                int imgIdx = 0;
                foreach (var imgFile in imgsList)
                {
                    if (!File.Exists(imgFile))
                    {
                        continue;
                    }

                    var img = iTextSharp.text.Image.GetInstance(imgFile);
                    img.ScaleToFit(doc.PageSize.Width-doc.LeftMargin-doc.RightMargin,
                        doc.PageSize.Height-doc.TopMargin-doc.BottomMargin);
                    img.Alignment=Element.ALIGN_CENTER;
                    doc.NewPage();
                    doc.Add(img);
                    Console.WriteLine($"{++imgIdx},{imgFile}");
                }
                doc.Close();
            }
        }
    }
}




public class PdfHeaderFooter : PdfPageEventHelper
{
    private PdfTemplate totalPages;
    private BaseFont baseFont;
    private string logoTitle;
    private string logoPath;
    private BaseColor baseColor = new BaseColor(64, 128, 128, 255);

    public PdfHeaderFooter(string logoTitleValue = "Analysis Report", string logoPathValue = null)
    {
        logoTitle = logoTitleValue;
        this.logoPath = logoPathValue;
    }

    public override void OnOpenDocument(PdfWriter writer, Document document)
    {
        baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false);
        totalPages = writer.DirectContent.CreateTemplate(50, 50);
    }

    public override void OnEndPage(PdfWriter writer, Document document)
    {
        var cb = writer.DirectContent;

        // --- HEADER ---
        float leftMargin = document.LeftMargin;
        float rightMargin = document.RightMargin;
        float pageWidth = document.PageSize.Width;
        float usableWidth = pageWidth - leftMargin - rightMargin;

        // Draw title
        ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT,
            new Phrase(logoTitle, new Font(Font.FontFamily.HELVETICA, 30, Font.BOLD, baseColor)),
            document.LeftMargin, document.Top + 30, 0);

        // Draw logo (right aligned)
        if (File.Exists(logoPath))
        {
            var logoImg = Image.GetInstance(logoPath);
            logoImg.ScaleToFit(70, 70);
            logoImg.SetAbsolutePosition(pageWidth - rightMargin - logoImg.ScaledWidth, document.Top + 10);
            cb.AddImage(logoImg);
        }

        // Line below header
        cb.SetLineWidth(10f);
        cb.SetColorStroke(baseColor);
        cb.MoveTo(leftMargin, document.Top);
        cb.LineTo(pageWidth - rightMargin, document.Top);
        cb.Stroke();

        // --- FOOTER ---
        float footerY = document.Bottom - 40;

        // Line above footer
        cb.SetLineWidth(10f);
        cb.SetColorStroke(baseColor);
        cb.MoveTo(leftMargin, footerY + 30);
        cb.LineTo(pageWidth - rightMargin, footerY + 30);
        cb.Stroke();

        // Page number: X/Y
        string text = "" + writer.PageNumber + "/";
        float len = baseFont.GetWidthPoint(text, 12);

        cb.BeginText();
        cb.SetFontAndSize(baseFont, 12);
        cb.SetTextMatrix(pageWidth / 2 - 30, footerY);
        cb.ShowText(text);
        cb.EndText();

        cb.AddTemplate(totalPages, pageWidth / 2 - 30 + len, footerY);
    }

    public override void OnCloseDocument(PdfWriter writer, Document document)
    {
        totalPages.BeginText();
        totalPages.SetFontAndSize(baseFont, 12);
        totalPages.SetTextMatrix(0, 0);
        totalPages.ShowText("" + (writer.PageNumber));
        totalPages.EndText();
    }
}

 

 

 

 

 

 

 

image

 

 

 

 

 

 

 

image

 

 

 

image

 

posted @ 2025-09-08 17:53  FredGrit  阅读(8)  评论(0)    收藏  举报