【问题标题】:How to use iTextSharp to convert to PDF如何使用 iTextSharp 转换为 PDF
【发布时间】:2017-05-19 02:21:07
【问题描述】:

平均售价:

<asp:Label ID="Label1" runat="server" Text="Folder Location: "></asp:Label> <asp:TextBox ID="tbFolder" runat="server"></asp:TextBox> 
<br /><br />
<asp:Label ID="Label2" runat="server" Text="Destination Folder: "></asp:Label> <asp:TextBox ID="tbDestination" runat="server"></asp:TextBox>
<br /><br />
<asp:Button ID="btnExecute" runat="server" Text="Button" OnClick="btnExecute_Click" />

代码隐藏:

public void btnExecute_Click(object sender, EventArgs e)
{
    try
    {
        strFolder = tbFolder.Text;
    }
    catch (Exception)
    {
        strFolder = "";
    }
    try
    {
        strDestination = tbDestination.Text;
    }
    catch (Exception)
    {
        strDestination = "";
    }
    try
    {
        strFileArray = Directory.GetFiles(strFolder, "*.tif");
        meregTiff(strFileArray);
    }
    catch (Exception)
    {
    }
}
public void meregTiff(string[] files)
{
    // Create the PDF with the proper parameters (change as you please)
    iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 0, 0, 0, 0);

    // Ensure the path to the folder is located where all the merged TIFF files will be saved as a PDF
    iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new System.IO.FileStream(strDestination + "/result2.pdf", System.IO.FileMode.Create));

    // Load each tiff files and convert it into a BITMAP and save it as a PDF
    // Recommendation: Use TRY/CATCH method to ensure any errors are handled properly...
    foreach (string image in files)
    {
        try
        {
            str = image.Substring(image.LastIndexOf("\\"));
            bm = new System.Drawing.Bitmap(Server.MapPath("~/TiffImages" + str)); //modify this to ensure the file exists (can be same as the page_load method)
            total = bm.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page);
        }
        catch (Exception ce) //getting error here... Parameter is invalid.
        {
        }

        document.Open();
        iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent;
        for (int k = 0; k < total; ++k)
        {
            bm.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, k);
            iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bm, System.Drawing.Imaging.ImageFormat.Bmp);
            // scale the image to fit in the page 
            img.ScalePercent(72f / img.DpiX * 100);
            img.SetAbsolutePosition(0, 0);
            cb.AddImage(img);
            document.NewPage();
        }
    }
    document.Close();
}

这里出现错误:catch (Exception ce) //getting error here... Parameter is invalid.

我该如何解决这个问题,以便将文件从tbFolder 文件夹中取出并作为一个 PDF 保存到 tbDestination 文件夹中。

【问题讨论】:

  • 仅供参考:为字符串赋值(就像在 strFolder = tbFolder.Text; 中所做的那样)永远不会引发异常。所以绝对没有必要用 try catch 来接受字符串赋值!
  • 在尝试中设置断点会发生什么?你能把它缩小到一行吗?
  • @PeterSchneider 我正在测试,但后来意识到你刚才所说的。谢谢。
  • 我将这一行更新为:bm = new System.Drawing.Bitmap(strFolder + str.Split('\\')[0]); //modify this to ensure the file exists (can be same as the page_load method),但我不断收到Parameters are not valid 错误。

标签: c# itextsharp


【解决方案1】:

首先,在您的情况下,mergeTiff 方法应该有一个 Document 属性,您可以在其中传入您创建一次的文档,因为此时您正在创建多个文档,其中每个文档都包含所有 tiff - 至少是所有保存在result2.pdf中。

只是为了让您入门(没有对其进行测试,显然应该进一步优化)...

public void btnExecute_Click(object sender, EventArgs e)
{   
    strFolder = tbFolder.Text;  
    strDestination = tbDestination.Text;
    strFileArray = Directory.GetFiles(strFolder, "*.tif");

    // Create the PDF with the proper parameters (change as you please)
    iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 0, 0, 0, 0);

    // Ensure the path to the folder is located where all the merged TIFF files will be saved as a PDF  
    iTextSharp.text.pdf.PdfWriter writer = 
       iTextSharp.text.pdf.PdfWriter.GetInstance(document, 
       new System.IO.FileStream(strDestination + "/result2.pdf", System.IO.FileMode.Create));

    meregTiff(document, writer, strFileArray);

}

public void meregTiff(iTextSharp.text.Document document, iTextSharp.text.PdfWriter pdfWriter, string[] files)
{ 
// Load each tiff files and convert it into a BITMAP and save it as a PDF
// Recommendation: Use TRY/CATCH method to ensure any errors are handled properly...
foreach (string image in files)
{
    try
    {
        str = image.Substring(image.LastIndexOf("\\"));
        bm = new System.Drawing.Bitmap(Server.MapPath("~/TiffImages" + str)); //modify this to ensure the file exists (can be same as the page_load method)
        total = bm.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page);
    }
    catch (Exception ce) //getting error here... Parameter is invalid.
    {
    }

    document.Open();
    iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent;
    for (int k = 0; k < total; ++k)
    {
        bm.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, k);
        iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bm, System.Drawing.Imaging.ImageFormat.Bmp);
        // scale the image to fit in the page 
        img.ScalePercent(72f / img.DpiX * 100);
        img.SetAbsolutePosition(0, 0);
        cb.AddImage(img);
        document.NewPage();
    }
   }
   document.Close();
 }

【讨论】:

  • 你能帮我修改一下吗?
  • 我已经更新了这个问题,因为我想使用两个文本框来获取文件夹和目标文件夹来保存 pdf。
  • 谢谢。但在bm = new System.Drawing.Bitmap(Server... 行中两次请求文件。
  • 我知道你在做什么,但它在 mergeTiff 函数中再次询问文件夹位置。这是我所拥有的:textsaver.flap.tv/lists/llg(我尝试保存三个 TIF 文件,总大小为 3 MB,PDF 为 63MB。也许您可以帮我编辑该代码?我只使用文件夹位置一次。
  • 您通常位于 ASP.NET 应用程序的虚拟目录中...您应该映射路径...。至少您需要进一步调整,因为您不允许自动从每个文件夹中读取...
【解决方案2】:
public void btnExecute_Click(string strFolder, string strDestination, string[] strFileArray)
    {
        //strFolder = tbFolder.Text;
        //strDestination = tbDestination.Text;
        //strFileArray = Directory.GetFiles(strFolder, "*.tif");

        // Create the PDF with the proper parameters (change as you please)
        iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 0, 0, 0, 0);

        // Ensure the path to the folder is located where all the merged TIFF files will be saved as a PDF  
        iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document,
           new System.IO.FileStream(strDestination + "/result2.pdf", System.IO.FileMode.Create));

        meregTiff(document, writer, strFileArray);

    }
    public void meregTiff(iTextSharp.text.Document document, iTextSharp.text.pdf.PdfWriter pdfWriter, string[] files)
    {
        // Load each tiff files and convert it into a BITMAP and save it as a PDF
        // Recommendation: Use TRY/CATCH method to ensure any errors are handled properly...
        foreach (string image in files)
        {
            Bitmap bm = null;
            int total = 0;
            string str = string.Empty;
            try
            {
                str = image.Substring(image.LastIndexOf("\\"));
                bm = new System.Drawing.Bitmap("TiffFolder"+ str); //modify this to ensure the file exists (can be same as the page_load method)
                total = bm.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page);
            }
            catch (Exception ce) //getting error here... Parameter is invalid.
            {
            }

            document.Open();
            iTextSharp.text.pdf.PdfContentByte cb = pdfWriter.DirectContent;
            for (int k = 0; k < total; ++k)
            {
                bm.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, k);
                iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bm, System.Drawing.Imaging.ImageFormat.Bmp);
                // scale the image to fit in the page 
                img.ScalePercent(72f / img.DpiX * 100);
                img.SetAbsolutePosition(0, 0);
                cb.AddImage(img);
                document.NewPage();
            }
        }
        document.Close();
    }

【讨论】:

  • 嗨安斯维尔。请详细说明您的解决方案。一个简单的代码示例通常没有那么有用。它是如何解决问题的?
猜你喜欢
  • 2014-09-29
  • 2022-03-07
  • 1970-01-01
  • 1970-01-01
  • 2011-06-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多