html - 使用数据库中的图像使用 itextsharp 创建 pdf

标签 html database image pdf itext

我有一个过程,其中 html 存储在带有图像链接的数据库中。图像也存储在数据库中。我创建了一个 Controller 操作,它从数据库中读取图像。我生成的路径类似于 /File/Image?path=Root/test.jpg . 此图像路径嵌入在 img 标签中的 html 中,如 <img alt="logo" src="/File/Image?path=Root/001.jpg" />

我正在尝试使用 itextsharp 从数据库中读取 html 并创建一个 pdf 文档

string _html = GenerateDocumentHelpers.CommissioningSheet(fleetId);
string _html = GenerateDocumentHelpers.CommissioningSheet(fleetId);
Document _document = new Document(PageSize.A4, 80, 50, 30, 65);
MemoryStream _memStream = new MemoryStream();
PdfWriter _writer = PdfWriter.GetInstance(_document, _memStream);
StringReader _reader = new StringReader(_html);            
HTMLWorker _worker = new HTMLWorker(_document);
_document.Open();            
_worker.Parse(_reader);
_document.Close();
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=Commissioning.pdf");
Response.ContentType = "application/pdf";
Response.Buffer = true;
Response.OutputStream.Write(_memStream.GetBuffer(), 0, _memStream.GetBuffer().Length);
Response.OutputStream.Flush();
Response.End();
return new FileStreamResult(Response.OutputStream, "application/pdf");

这段代码给我一个非法字符错误。这来自图像标签,无法识别?和 = 字符,有没有一种方法可以用 img 标签渲染这个 html,这样当我创建一个 pdf 时,它会从数据库中渲染 html 和图像并创建一个 pdf,或者如果 itextsharp 不能这样做,你能提供给我吗是否有任何其他第三方开源工具可以完成此任务?

最佳答案

如果图像源不是包含协议(protocol)的完全限定 URL,则 iTextSharp 假定它是基于文件的 URL。解决方案是将所有图像链接以 http://YOUR_DOMAIN/File/Image?path=Root/001.jpg 的形式转换为绝对链接。 .

您还可以在解析器上设置一个全局属性,其工作方式与 HTML 几乎相同 <BASE>标签:

//Create a provider collection to set various processing properties
System.Collections.Generic.Dictionary<string, object> providers = new System.Collections.Generic.Dictionary<string, object>();
//Set the image base. This will be prepended to the SRC so watch your forward slashes
providers.Add(HTMLWorker.IMG_BASEURL, "http://YOUR_DOMAIN");
//Bind the providers to the worker
worker.SetProviders(providers);
worker.Parse(reader);

下面是针对 iTextSharp 5.1.2.0 的完整工作 C# 2010 WinForms 应用程序,它展示了如何使用相对图像并使用全局提供程序设置其基础。一切都与您的代码几乎相同,尽管我通过了一堆 using语句以确保正确清理。确保观察所有内容的前导和尾随正斜杠,基本 URL 仅直接前置 SRC属性,如果没有正确完成,您可能会得到双斜线。我在这里强硬地使用域,但您应该能够轻松使用 System.Web.HttpContext.Current.Request对象。

using System;
using System.IO;
using System.Windows.Forms;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;

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

        private void Form1_Load(object sender, EventArgs e)
        {

            string html = @"<img src=""/images/home_mississippi.jpg"" />";
            string outputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "HtmlTest.pdf");
            using (FileStream fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
                using (Document doc = new Document(PageSize.TABLOID)) {
                    using (PdfWriter writer = PdfWriter.GetInstance(doc, fs)) {
                        doc.Open();

                        using (StringReader reader = new StringReader(html)) {
                            using (HTMLWorker worker = new HTMLWorker(doc)) {
                                //Create a provider collection to set various processing properties
                                System.Collections.Generic.Dictionary<string, object> providers = new System.Collections.Generic.Dictionary<string, object>();
                                //Set the image base. This will be prepended to the SRC so watch your forward slashes
                                providers.Add(HTMLWorker.IMG_BASEURL, "http://www.vendiadvertising.com");
                                //Bind the providers to the worker
                                worker.SetProviders(providers);
                                worker.Parse(reader);
                            }
                        }

                        doc.Close();
                    }
                }
            }

            this.Close();
        }
    }
}

关于html - 使用数据库中的图像使用 itextsharp 创建 pdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9457643/

相关文章:

mysql - 在查询中使用已选择的单元格

database - 使用 Perl,如何使用 dbh csv_tables 从标准输入读取 CSV 字符串?

java - 将图像加载到程序(与 jar 一起使用)

javascript - 为什么我不能让我的图像出现在表格单元格/节点中..也许我可以得到一些结论?

ios - UIView 动画仅在呈现静态图像时触发

javascript - 如何让这个由 Javascript 设置固定位置的 DIV 留在包含的 DIV 中?

javascript - 在 D3 树中,如何以编程方式关闭选定深度的所有节点(例如仅孙子节点)(无需单击节点)

python - Flask 的 render_template() 问题

html - 如何将 mime 类型添加到 htaccess 文件?

SQL 列合并和聚合函数