0

我正在使用 iTextSharp 生成 PDF。我有一个 HTMl 页面,我正在阅读 HTML 页面然后生成 PDF。但问题是页面的一半是 PDF,而页面的另一半正在用完 PDF 页面.我的意思是页面的一半以 PDF 格式显示。而页面的一半以 PDF 格式剪切。

我的代码在加载事件中是这样的..

    string fileContents;
    string FilePath = Server.MapPath("print-withoutlogin.html");
    StreamReader mstrFileStreamReader = new StreamReader(FilePath);
    try
    {
        fileContents = mstrFileStreamReader.ReadToEnd();
        byte[] result = createPDF(fileContents.ToString()).GetBuffer();

        Response.Clear();
        Response.AddHeader("Content-Length", result.Length.ToString());
        Response.ContentType = "application/pdf";
        Response.AddHeader("Accept-Ranges", "bytes");
        Response.Buffer = true;
        Response.AddHeader("Expires", "0");
        Response.AddHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        Response.AddHeader("Pragma", "public");
        Response.AddHeader("content-Transfer-Encoding", "binary");
        Response.AddHeader("Content-Disposition", "attachment; filename=kartik.pdf");
        Response.BinaryWrite(result);
        Response.Flush();
        Response.End();
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        mstrFileStreamReader.Close();
    }

 private MemoryStream createPDF(string html)
 {
    MemoryStream msOutput = new MemoryStream();
    TextReader reader = new StringReader(html);

    Document document = new Document(PageSize.A4, 0, 0, 50, 50);

    PdfWriter writer = PdfWriter.GetInstance(document, msOutput);
    HTMLWorker worker = new HTMLWorker(document);
    //worker.SetStyleSheet(styles);


    // step 4: we open document and start the worker on the document 
    document.Open();
    worker.StartDocument();
    // step 5: parse the html into the document      
    worker.Parse(reader);
    // step 6: close the document and the worker     
    worker.EndDocument();
    worker.Close();
    document.Close();

    return msOutput;
 }
4

1 回答 1

0

您是否考虑过使用 Crystal Reports?我发现它更容易,你可以使用

pdfStream = (MemoryStream)report.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
于 2012-12-04T11:01:41.923 回答