簡體   English   中英

使用iTextSharp將圖像添加到PDF並正確縮放

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM