将html页面导出为pdf [英] exporting html page to pdf

查看:260
本文介绍了将html页面导出为pdf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我的任务是生成pdf格式的发票.我有一个html模板.我用名称,地址,联系电话将一些html内容替换为一个字符串.现在,我无法使用itextsharper获取pdf.我没有在PDF中获得CSS,完美的设计. pdf是使用itextsharper生成的.谁能帮助我.

Hi all,

My task is to generate the invoice in pdf. I have an html template. i am replacing some of the html content with name, address, contact number into a string . Now i am unable to get the pdf by using the itextsharper. I am not getting the css, perfect design in the pdf. pdf is generating by using itextsharper. Can anyone help me.

推荐答案

代码:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using iTextSharp.text;
using iTextSharp.text.html;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
using System.IO;
using System.util;
using System.Net;
using System.Xml;

protected void btn_submit_Click(object sender, EventArgs e)
    {
        using (StreamReader reader = new StreamReader(Server.MapPath("~") + "/App_Data/test.html"))
        {
            String line = reader.ReadToEnd();
            Text2PDF(line);
        }
    }

    protected void Text2PDF(string PDFText)
    {
        //HttpContext context = HttpContext.Current;
        StringReader reader = new StringReader(PDFText);

        //Create PDF document 
        Document document = new Document(PageSize.A4);
        HTMLWorker parser = new HTMLWorker(document);

        string PDF_FileName = Server.MapPath("~") + "/App_Data/PDF_File.pdf";
        PdfWriter.GetInstance(document, new FileStream(PDF_FileName, FileMode.Create));
        document.Open();

        try
        {
            parser.Parse(reader);
        }
        catch (Exception ex)
        {
            //Display parser errors in PDF. 
            Paragraph paragraph = new Paragraph("Error!" + ex.Message);
            Chunk text = paragraph.Chunks[0] as Chunk;
            if (text != null)
            {
                text.Font.Color = BaseColor.RED;
            }
            document.Add(paragraph);
        }
        finally
        {
            document.Close();
            DownLoadPdf(PDF_FileName);
        }
    }

    private void DownLoadPdf(string PDF_FileName)
    {
        WebClient client = new WebClient();
        Byte[] buffer = client.DownloadData(PDF_FileName);
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-length", buffer.Length.ToString());
        Response.BinaryWrite(buffer);
    }


这篇关于将html页面导出为pdf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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