使用itextsharp将带图像的HTML转换为PDF时出错

时间:2013-04-17 09:11:34

标签: asp.net-mvc itextsharp

在我的应用程序中,首先允许用户使用CKEDITOR创建html文档,用户可以在其中创建html文档并可以插入图像,表单字段等。生成的HTML文档将转换为PDF。 如果HTML文档包含纯文本而不是PDF文件成功创建但如果用户在其中插入图像而不是给出错误。 用于创建PDF文档的代码。

public ActionResult CreateFile(FormCollection data)
    {
        var filename = data["filename"];
        var htmlContent = data["content"];
        string sFilePath = Server.MapPath(_createdPDF + filename + ".html");
        htmlContent = htmlContent.Trim();
        if (!System.IO.File.Exists(sFilePath))
        {
            using (FileStream fs = new FileStream(sFilePath, FileMode.Create))
            {
                using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8))
                {
                    w.Write(htmlContent);
                }
            }
            createPDF(sFilePath);
        }

        return View();
    }

    private MemoryStream createPDF(string sFilePath)
    {
        string filename = Path.GetFileNameWithoutExtension(sFilePath);
        string name = Server.MapPath(_createdPDF + filename + ".pdf");
        MemoryStream ms = new MemoryStream();
        TextReader tr = new StringReader(sFilePath);
        Document document = new Document(PageSize.A4, 30, 30, 30, 30);
        string urldir = Request.Url.GetLeftPart(UriPartial.Path);
        urldir = urldir.Substring(0, urldir.LastIndexOf("/") + 1);
        Response.Write(urldir);
        PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(name, FileMode.Create));
        document.Open();
        string htmlText = "";
        StreamReader sr;
        sr = System.IO.File.OpenText(sFilePath);
        htmlText = sr.ReadToEnd();
        sr.Close();
        WebClient wc = new WebClient();
        Response.Write(htmlText);
        var props = new Dictionary<string, Object>();
        props["img_baseurl"] = @"C:\Documents and Settings\shubham\My Documents\visdatemplatemanger\visdatemplatemanger\";
        List<IElement> htmlarraylist = HTMLWorker.ParseToList(new StringReader(htmlText), null,props);
        for (int k = 0; k < htmlarraylist.Count; k++)
        {
            document.Add((IElement)htmlarraylist[k]);
        }
        document.Close();
        System.IO.File.Delete(sFilePath);
        UploadURL(name);
        return ms;
    }

如果图像包含在HTML文档中,我得到的错误是:

Could not find a part of the path 'C:\Program Files\Common Files\Microsoft Shared\PDFimages\rectangle-shape.png'.

1 个答案:

答案 0 :(得分:0)

iTextSharp将尝试解析基于HTTP的文档的相对图像,但是您需要提供的文件系统提供绝对路径或为其提供搜索基础。

//Image search base, path will be concatenated directly so make sure it contains a trailing slash
var props = new Dictionary<string, Object>();
props["img_baseurl"] = @"c:\images\";

//Include the props from above
htmlarraylist = HTMLWorker.ParseToList(sr, null, props);