0

在我的应用程序中,首先允许用户使用 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'.
4

1 回答 1

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);
于 2013-04-17T13:48:09.057 回答