从PDF文件创建图像或PdfTemplate

时间:2011-09-02 07:55:23

标签: c# pdf-generation itextsharp

在使用itextsharp库生成pdf时,我遇到了这种方法: -

iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(itextsharp.text.pdf.PdfTemplate);

在哪里,我们可以从PdfTemplate获取Image实例。但是,我不知道如何创建PdfTemplate,并且没有构造函数采用pdf文件名或流。

为什么我想要这样:我想从PDF文件创建一个图像,然后将此图像转换为另一个pdf文件。

有谁知道如何创建PdfTemplate对象?

1 个答案:

答案 0 :(得分:6)

遗憾的是PdfTemplate并不完全是您的想法。 iText和iTextSharp是PDF生成器,但不是PDF渲染器,这是将PDF转换为图像所需的。

尽管如此,根据您所寻找的品质,您仍然可以实现目标。

PdfTemplate的一个常见用途是子类PdfImportedPage。如果您从Image创建PdfImportedPage,则无法创建JPG或PNG或任何栅格,实际上您的页面的完整版本会被Image包裹起来宾语。这意味着您可以应用ScaleAbsolute()或任何您想要的变换,但是当您将其添加到输出PDF时,任何文本仍然是真实文本(因此可选择)。这是质量进入的部分。如果你开始缩放Image它会(数学上)完美地缩放,但在视觉上它可能在Adobe Reader之类的东西中呈现不完美。如果你放大它会很好,但许多屏幕程序不能很好地渲染小类型。这是否是一个问题,我不知道。

无论如何,下面的代码是一个完整的工作样本,目标是iTextSharp 5.1.1.0。它从现有PDF中读取页面,将其缩放50%并将其添加到输出PDF。

using System;
using System.ComponentModel;
using System.Text;
using System.Windows.Forms;
using System.IO;
using iTextSharp.text.pdf;
using iTextSharp.text;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //PDF file to pull the first page from
            string inputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Input.pdf");
            //PDF file to output
            string outputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Output.pdf");


            using (FileStream fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                using (Document doc = new Document())
                {
                    using (PdfWriter w = PdfWriter.GetInstance(doc, fs))
                    {
                        //Open our PDF for writing
                        doc.Open();

                        //We need a reader to pull pages from
                        PdfReader r = new PdfReader(inputFile);

                        //Get the first page of our source PDF
                        PdfImportedPage importedPage = w.GetImportedPage(r, 1);

                        //Insert a new page into our output PDF
                        doc.NewPage();

                        //Create an Image from the imported page
                        iTextSharp.text.Image Img = iTextSharp.text.Image.GetInstance(importedPage);

                        //Just to show why we are using an Image, scale the Image to 50% width and height of the original page
                        Img.ScaleAbsolute(importedPage.Width / 2, importedPage.Height / 2);

                        //Add the Image to the page
                        doc.Add(Img);

                        //Close our output PDF
                        doc.Close();
                    }
                }
            }
            this.Close();
        }
    }
}