在 c# 中使用 itextsharp 将图像转换为 PDF

本文关键字:图像 转换 PDF itextsharp | 更新日期: 2023-09-27 18:30:52

我想使用 itextsharp 将包含图像和网格视图的页面转换为 pdf 表单。下面是我的代码

  string attachment = "attachment; filename=Report.pdf";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/pdf";
        StringWriter stw = new StringWriter();
        HtmlTextWriter htextw = new HtmlTextWriter(stw);
        divText.RenderControl(htextw);   //image is place inside 
        GridView1.RenderControl(htextw);           
        Document document = new Document();
        PdfWriter.GetInstance(document, Response.OutputStream);
        document.Open();
        StringReader str = new StringReader(stw.ToString());
        HTMLWorker htmlworker = new HTMLWorker(document);
        htmlworker.Parse(str);
        document.Close();
        Response.Write(document);
        Response.End();

我设法将网格视图转换为PDF,但无法转换图像。图像放置在div 调用divText 中。有人可以帮助我吗?

在 c# 中使用 itextsharp 将图像转换为 PDF

我建议尝试以下代码并根据您的情况进行修改

public static void ConvertImageToPdf(string srcFilename, string dstFilename)
    {
        iTextSharp.text.Rectangle pageSize = null;
        using (var srcImage = new Bitmap(srcFilename))
        {
            pageSize = new iTextSharp.text.Rectangle(0, 0, srcImage.Width, srcImage.Height);
        }
        using (var ms = new MemoryStream())
        {
            var document = new iTextSharp.text.Document(pageSize, 0, 0, 0, 0);
            iTextSharp.text.pdf.PdfWriter.GetInstance(document, ms).SetFullCompression();
            document.Open();
            var image = iTextSharp.text.Image.GetInstance(srcFilename);
            document.Add(image);
            document.Close();
            File.WriteAllBytes(dstFilename, ms.ToArray());
        }
    }

另请参阅问题

以上代码说明点击这里

使用图像 itextsharp

更改图像 URL 路径,如"C:''images''文件名.jpg"

您的代码示例看起来不错,缺少 IImageProvider 的实现。默认情况下,HTMLWorker只能处理具有绝对 URL 的图像。因此,这里有一个简单的实现来帮助您入门:

// handle <img> tags in any System.Web.UI.Control (GridView) with:
// 1. base64 Data URI scheme - https://en.wikipedia.org/wiki/Data_URI_scheme
// 2. relative URLs on local server
// 3. absolute URLs on a remote/local server (DEFAULT)
public class ImageHander : IImageProvider
{
    public string BaseUri { get; set; }
    public static Regex Base64 = new Regex(
        @"^data:image/(?<mediaType>[^;]+);base64,(?<data>.*)",
        RegexOptions.Compiled
    );
    // alias: using iTextImage = iTextSharp.text.Image;
    public iTextImage GetImage(string src,
        IDictionary<string, string> attrs,
        ChainedProperties chain,
        IDocListener doc)
    {
        Match match;
        // [1]
        if ((match = Base64.Match(src)).Length > 0)
        {
            return iTextImage.GetInstance(
                Convert.FromBase64String(match.Groups["data"].Value)
            );
        }
        // [2]
        if (!src.StartsWith("http", StringComparison.OrdinalIgnoreCase))
        {
            src = HttpContext.Current.Server.MapPath(
                new Uri(new Uri(BaseUri), src).AbsolutePath
            ); 
        }
        return iTextImage.GetInstance(src);
    }
}

然后,在代码隐藏中使用实现,如下所示(按钮事件处理程序):

protected void ProcessHtml(object sender, CommandEventArgs e)
{
    Response.ContentType = "application/pdf";
    Response.AppendHeader("Content-Disposition", "attachment; filename=table.pdf");
    using (Document document = new Document())
    {
        PdfWriter.GetInstance(document, Response.OutputStream);
        document.Open();
        var html = new StringBuilder();
        using (var stringWriter = new StringWriter(html))
        {
            using (var htmlWriter = new HtmlTextWriter(stringWriter))
            {
                // replace 'ConvertControlToPdf' with **YOUR** GridView control Id!
                ConvertControlToPdf.RenderControl(htmlWriter);
            }
        }
        var providers = new Dictionary<string, Object>();
        // HTMLWorker does **NOT** understand relative URLs, so
        // make existing ones in HTML source absolute, and handle 
        // base64 Data URI schemes
        var ih = new ImageHander() { BaseUri = Request.Url.ToString() };
        // dictionary key 'img_provider' is **HARD-CODED**, in 
        // iTextSharp 5.0.0 - 5.0.5, so you may need to use next line
        // providers.Add("img_provider", ih);
        providers.Add(HTMLWorker.IMG_PROVIDER, ih);
        //            ^^^^^^^^^^^^^^^^^^^^^^^ - constant added in 5.0.6
        using (var sr = new StringReader(html.ToString()))
        {
            foreach (IElement element in HTMLWorker.ParseToList(
                sr, null, providers))
            {
                PdfPTable table = element as PdfPTable;
                document.Add(element);
            }
        }
    }
    Response.End();
}

不确定您运行的是什么版本的 iTextSharp,因此请注意有关上述HTMLWorker.IMG_PROVIDER const的内联注释。