简体   繁体   中英

How to export multiple charts asp.net to a single document PDF using itextSharp?

I want to export two Charts Asp.net to a single document PDF using iTextSharp.

For one chart, I could do it :

Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
using (MemoryStream stream = new MemoryStream())
{
    Chart1.SaveImage(stream, ChartImageFormat.Png);
    iTextSharp.text.Image chartImage = iTextSharp.text.Image.GetInstance(stream.GetBuffer());
    chartImage.ScalePercent(75f);
    pdfDoc.Add(chartImage);
    pdfDoc.Close();

    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition", "attachment;filename=Charts.pdf");
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.Write(pdfDoc);
    Response.End();
}

BUT, I can't export two Charts in the same time...

Someone has the answer ? thank you very much...

Perhaps you're referencing the same chart, or not cleaning up the MemoryStream ? Here's a simple example that generates two different charts, and then adds them to the Document .

First a helper method to generate some sample data:

byte[] GetChartImage(params int[] points)
{
    using (var stream = new MemoryStream())
    {
        using (var chart = new Chart())
        {
            chart.ChartAreas.Add(new ChartArea());
            Series s = new Series();
            for (int i = 0; i < points.Length; ++i)
            {
                s.Points.AddXY(points[i], points[i]);
            }
            chart.Series.Add(s);
            chart.SaveImage(stream, ChartImageFormat.Png);
        }
        return stream.ToArray();
    }
}

Then add the charts:

Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=charts.pdf");
using (Document document = new Document())
{
    PdfWriter.GetInstance(document, Response.OutputStream);
    document.Open();
    document.Add(Image.GetInstance(GetChartImage(3, 5, 7)));
    document.Add(Image.GetInstance(GetChartImage(2, 4, 6, 8)));
}
Response.End();

The PDF output:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM