【问题标题】:Unable to Export HTML Markup to PDF using iTextSharp API in asp.net using C#?无法使用 C# 在 asp.net 中使用 iTextSharp API 将 HTML 标记导出为 PDF?
【发布时间】:2014-01-07 09:24:02
【问题描述】:

我有一个HTML 标记,其中包含HTML TableImages。我正在使用iTextSharp API 转换HTML markup to PDF。但是,不幸的是,iTextSharp 无法将包含图像和表格的HTML 标记导出为 PDF。

错误:找不到网络路径。

结果必须是:

代码:

using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using System.Data.SqlClient;
using System.Text;
using iTextSharp.text.html.simpleparser;
 public string strSelectUserListBuilder = @" <div style='width: 50%; border: 1 solid #000000; padding-bottom: 100; padding-left: 100;
        padding-right: 100; text-align: justify; text-justify: inter-word;'>
        <br />
        <table>
            <tr>
                <td>
                    <div id='divLeft'>
                        <p>
                            <img src='/images/log_out.png'  width='200' height='100' /></p>
                        <h2>
                            Packing slip</h2>
                        <h3>
                            Place this slip inside the box with your device.</h3>
                        <div id='divDeviceList' style='width: 600; text-align: left;' border='0' cellpadding='3'
                            cellspacing='1' rules='BOTH' frame='BOX'>
                            <table style='width: 600;'>
                                <tr>
                                    <td>
                                       <strong> ITEM</strong>
                                    </td>
                                    <td>
                                       <strong>  OFFER</strong>
                                    </td>
                                </tr>
                                <tr>
                                    <td>
                                        iPhone 5 32GB (AT&T)
                                    </td>
                                    <td>
                                        $205.00
                                    </td>
                                </tr>

                                <tr>
                                    <td align='right'>
                                    <hr />
                                     <strong><h3>Total Offer: &nbsp;</h3></strong>
                                    </td>
                                    <td>
                                    <hr />
                                      <strong> <h3>  $215.00</h3></strong>
                                    </td>
                                </tr>

                            </table>


                        </div>

                            <h3>
                                You have until 01/29/2014 to ship your device.</h3>
                        <p style='padding:10;'>
                            <i>If you send your device after the expiration date we cannot honor your initial offer.
                                We will not accept devices that have been reported lost or stolen.</i></p>
                        <br />
                    </div>
                </td>
                <td>
                    <div id='divRight'>
                     <div style='text-align:right;padding:15;'> <img src='/images/google-login.png' alt='barcode' /></div>
                        <table cellpadding='3' style='border: 1 solid orange;padding:20;'>

                        </tr>
                            <tr align='center'>
                                <td>
                                   <img src='/images/google-login.png'  />
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <h3>
                                        'Find my iPhone' must be turned off</h3>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    This feature locks your device and will delay or reduce payment.
                                </td>
                            </tr>
                            <tr>
                                <td>
                                 <strong>How to deactivate:</strong></td>
                            </tr>
                            <tr>
                                <td>
                                    1. Tap the “settings” icon on your homescreen.</td>
                            </tr>
                            <tr>
                                <td>
                                    2. Tap iCloud from the settings menu. </td>
                            </tr>
                            <tr>
                                <td>
                                    3. If 'Find My iPhone' is on, tap the slider to turn it off.</td>
                            </tr>
                        </table>
                    </div>";

protected void HTMLToPDF()
    {

        String htmlText = strSelectUserListBuilder.ToString();
        Document document = new Document();
        PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "MySamplePDF.pdf", FileMode.Create));
        document.Open();
        iTextSharp.text.html.simpleparser.HTMLWorker hw =
                     new iTextSharp.text.html.simpleparser.HTMLWorker(document);
        hw.Parse(new StringReader(htmlText));
        document.Close();
    }

protected void Page_Load(object sender, EventArgs e)
{
         HTMLToPDF();
}

我知道这个错误是由图像路径引起的。但是,无法解决。

有什么办法吗?

帮助赞赏!

【问题讨论】:

  • 你成功了吗?
  • pdf 不是按照我展示的设计创建的...!它扭曲了...... :(
  • 是的,但是您是否尝试过输入图像的完整物理路径(正如我在回答中所建议的那样)?
  • 是的!图像渲染但它扭曲了......布局......! :(

标签: c# asp.net itextsharp html-to-pdf pdf-conversion


【解决方案1】:

看看:creating pdf with itextsharp with images from database

您需要在每个 img 元素的 src 属性中提供完整的物理路径(例如 &lt;img src="c:\myproject\images\image.jpg"/&gt;),或者可以告诉 iTextSharp 您所有图像的物理基础文件夹。

【讨论】:

    【解决方案2】:

    我能够通过使用特殊提供程序正确呈现我的 html

    var baseUrl = string.Format("{0}://{1}", Request.Url.Scheme, Request.Url.Authority);
    
    var html = ...;
    
    Response.Clear();
    Response.ClearContent();
    Response.ClearHeaders();
    
    Response.ContentEncoding = Encoding.UTF8;
    Response.AddHeader("content-disposition", string.Format("attachment; filename={0}.pdf", fileName));
    Response.ContentType = "application/pdf";
    
    using (var ms = new MemoryStream())
    {
    
        using (var doc = new Document())
        {                       
            using (var writer = PdfWriter.GetInstance(doc, ms))
            {
                doc.Open();
    
                var rootProvider = new CustomRootProvider(baseUrl, Request.PhysicalApplicationPath); //Server.MapPath(Request.ApplicationPath)
    
                FontFactory.RegisterDirectories();
    
                var htmlContext = new HtmlPipelineContext(null);
    
                htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());                           
    
                htmlContext.SetImageProvider(rootProvider);
    
                htmlContext.SetLinkProvider(rootProvider);
    
                htmlContext.CharSet(Encoding.UTF8);
    
                var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true);
    
                var pipeline = new CssResolverPipeline(cssResolver,
    
                new HtmlPipeline(htmlContext, new PdfWriterPipeline(doc, writer)));
    
                var worker = new XMLWorker(pipeline, true);
    
                var p = new XMLParser(worker);
    
                using(var htmlStream = new MemoryStream(Encoding.UTF8.GetBytes(html)))
                {
                    p.Parse(htmlStream, Encoding.UTF8);                         
                }       
    
                writer.CloseStream = false;
            }
            doc.Close();
        }
        ms.Position = 0;                    
        Response.BinaryWrite(ms.ToArray());
    }
    
    Response.Flush();
    Response.End();
    
    ...
    
    public class CustomRootProvider : AbstractImageProvider, ILinkProvider
    {
        private string _baseUrl;
        private string _basePath;
        public CustomRootProvider(string baseUrl, string basePath)
        {
            _baseUrl = baseUrl;     
        }
    
        public override Image Retrieve(string src)
        {       
            var siteUrl = string.IsNullOrEmpty(_baseUrl) ? HttpContext.Current.Request.Url.AbsoluteUri.Replace(HttpContext.Current.Request.Url.PathAndQuery, string.Empty) : _baseUrl;
    
            siteUrl = VirtualPathUtility.RemoveTrailingSlash(siteUrl);      
    
            if (Uri.IsWellFormedUriString(src, UriKind.Relative))
            {
                src = new Uri(new Uri(siteUrl), src).ToString();            
            }
    
            try
            {
                return Image.GetInstance(src);
            }
            catch (Exception)
            {                       
                return Image.GetInstance(new Uri(new Uri(siteUrl), "/Content/Images/noimage.png").ToString());
            }
    
        }
    
        public override string GetImageRootPath()
        {
            return string.IsNullOrEmpty(_basePath) ? HttpContext.Current.Request.PhysicalApplicationPath : _basePath;
            //HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath);
        }
    
        public string GetLinkRoot()
        {
            return string.IsNullOrEmpty(_baseUrl)
                ? HttpContext.Current.Request.Url.AbsoluteUri.Replace(HttpContext.Current.Request.Url.PathAndQuery, string.Empty)
                : _baseUrl;
        }
    }
    

    但是在某些主机上出现了 html unicode 符号的奇怪问题(在德国机器上还可以,但在俄罗斯机器上呈现不正确)。我试图用 iTextSharp fontfactory 注册不同的字体,以使用不同的标记(css 规则、字体等)。没有什么帮助我。这以使用 wkhtmltopdf 和包装器 Pechkin (互联网上提供不同的包装器)结束。 wkhtmltopdf 开箱即用!:

    var config = new GlobalConfig().SetMargins(0, 0, 0, 0).SetPaperSize(PaperKind.A4);
    
    var pdfWriter = new SynchronizedPechkin(config);
    
    var bytes = pdfWriter.Convert(new Uri(dataUrl));
    
    Response.BinaryWrite(bytes);
    

    强烈推荐!

    【讨论】:

      猜你喜欢
      • 2013-08-25
      • 2011-12-31
      • 1970-01-01
      • 1970-01-01
      • 2012-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-14
      相关资源
      最近更新 更多