使用c#中的itextsharp将图像转换为Pdf

时间:2016-01-19 05:53:15

标签: c# pdf itextsharp

我想使用itextsharp将包含图像和gridview的页面转换为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();

我设法将gridview转换为pdf但无法转换图像。图像放在div调用divText中。有人可以帮我吗?

3 个答案:

答案 0 :(得分:0)

我建议您尝试使用以下代码并根据您进行修改

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

另请参阅Question

click here

以上代码的说明

working with images itextsharp

答案 1 :(得分:0)

更改图片网址路径,例如" C:\ images \ Filename.jpg"

答案 2 :(得分:0)

您的代码示例看起来不错,它缺少IImageProvider的实现。默认情况下,HTMLWorker只能 处理带有绝对网址的图片。所以这是一个简单的实现,可以帮助您入门:

// 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的内联评论。