创建pdf与itextsharp与数据库的图像 [英] creating pdf with itextsharp with images from database

查看:138
本文介绍了创建pdf与itextsharp与数据库的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个过程,其中html是存储在数据库中的图像链接。图像也存储在db中。我创建了一个控制器操作,从数据库读取图像。我生成的路径是类似 /File/Image?path=Root/test.jpg
此图像路径嵌入在img标签中的html中,例如< img alt =logosrc =/ File / Image?path = Root / 001.jpg/> code>

I have a process where the html is stored in database with image links. the images are also stored in db as well. I've created a controller action which reads the image from database. the path I'm generating is something like /File/Image?path=Root/test.jpg. this image path is embedded in html in img tag like <img alt="logo" src="/File/Image?path=Root/001.jpg" />

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

I'm trying to use itextsharp to read the html from the database and create a pdf document

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不能做到,你能提供给我任何其他可以完成此任务的第三方开源工具?

This code gives me an illegal character error. this comes from the image tag, it is not recognizing ? and = characters, is there a way I can render this html with img tag so that when i create a pdf it renders the html and image from the database and creates a pdf or if itextsharp can't do it, can you provide me with any other third party open source tools that can accomplish this task?

我需要您的帮助。

推荐答案

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

If the image source isn't a fully qualified URL including protocol then iTextSharp assumes that it is a file-based URL. The solution is to just convert all image links to absolute in the form http://YOUR_DOMAIN/File/Image?path=Root/001.jpg.

您还可以在解析器上设置一个全局属性,它的工作方式与HTML < BASE> p>

You can also set a global property on the parser that works pretty much the same as the HTML <BASE> tag:

//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);

下面是一个完整的工作C#2010 WinForms应用程序的目标iTextSharp 5.1.2.0显示如何使用图像并使用全局提供程序设置其基础。一切都与你的代码几乎一样,虽然我通过一堆使用语句来确保适当的清理。确保在所有事情上观察前导和尾随前斜线,基本URL只直接在前面加上 SRC 属性,如果不正确,可能会出现双斜线。我在这里硬盘一个域,但你应该能够轻松地使用 System.Web.HttpContext.Current.Request 对象。

Below is a full working C# 2010 WinForms app targeting iTextSharp 5.1.2.0 that shows how to use a relative image and set its base using the global provider. Everything is pretty much the same as your code, although I through in a bunch of using statements to ensure proper cleanup. Make sure to watch the leading and trailing forward slashes on everything, the base URL gets prepended directly only the SRC attribute and you might end up with double-slashes if its not done correctly. I'm hard-balling a domain in here but you should be able to easily use the System.Web.HttpContext.Current.Request object.

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();
        }
    }
}

这篇关于创建pdf与itextsharp与数据库的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆