如何解决使用ASP.NET Core中的iTextSharp生成PDF中的图表,图形
我需要在ASP.NET Core 3.1的服务器端生成PDF文档。我正在使用iTextSharp生成PDF。我可以使用iTextSharp在PDF中创建数据表。但是,我找不到使用同一库将图表添加到PDF的解决方案。
我使用过ChartJS和其他类似的程序包,但是它们都不能让我在后端创建图表并将其创建为要嵌入PDF的图像。
解决方法
更新2020年12月12日
创建excel
,然后转换为pdf。 Essential XlsIO
是本机.NET类库,可用于创建和修改Microsoft Excel文件。
[Route("/chart")]
public IActionResult CreateChart()
{
using (ExcelEngine excelEngine = new ExcelEngine())
{
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
IWorkbook workbook = application.Workbooks.Create(1);
IWorksheet sheet = workbook.Worksheets[0];
//Inserts the sample data for the chart
sheet.Range["A1"].Text = "Month";
sheet.Range["B1"].Text = "Product A";
sheet.Range["C1"].Text = "Product B";
//Months
sheet.Range["A2"].Text = "Jan";
sheet.Range["A3"].Text = "Feb";
sheet.Range["A4"].Text = "Mar";
sheet.Range["A5"].Text = "Apr";
sheet.Range["A6"].Text = "May";
//Create a random Data
Random r = new Random();
for (int i = 2; i <= 6; i++)
{
for (int j = 2; j <= 3; j++)
{
sheet.Range[i,j].Number = r.Next(0,500);
}
}
IChartShape chart = sheet.Charts.Add();
//Set chart type
chart.ChartType = ExcelChartType.Line;
//Set Chart Title
chart.ChartTitle = "Product Sales comparison";
//Set first serie
IChartSerie productA = chart.Series.Add("ProductA");
productA.Values = sheet.Range["B2:B6"];
productA.CategoryLabels = sheet.Range["A2:A6"];
//Set second serie
IChartSerie productB = chart.Series.Add("ProductB");
productB.Values = sheet.Range["C2:C6"];
productB.CategoryLabels = sheet.Range["A2:A6"];
//Saving the workbook as stream
//FileStream stream = new FileStream("Chart.xlsx",FileMode.Create,FileAccess.ReadWrite);
//workbook.SaveAs(stream);
//Initialize XlsIO renderer.
XlsIORenderer renderer = new XlsIORenderer();
//Convert Excel document into PDF document
Syncfusion.Pdf.PdfDocument pdfDocument = renderer.ConvertToPDF(sheet);
MemoryStream stream = new MemoryStream();
pdfDocument.Save(stream);
stream.Flush(); //Always catches me out
stream.Position = 0; //Not sure if this is required
//stream.Dispose();
return File(stream,"application/pdf","chart.pdf");
}
}
使用ASPNET Core 3.1中的 iTextsharp 生成带有图像的PDF
这是action
的代码。
[Route("/pdf")]
public FileStreamResult GeneratePDFwithImage()
{
var imagepath = System.IO.Path.Combine(_env.WebRootPath,"/images") + "/test.png";
Document doc = new Document();
MemoryStream stream = new MemoryStream();
PdfWriter pdfWriter = PdfWriter.GetInstance(doc,stream);
pdfWriter.CloseStream = false;
doc.Open();
doc.Add(new Paragraph("Hello World"));
Image png = Image.GetInstance(imagepath);
doc.Add(png);
doc.Close();
stream.Flush(); //Always catches me out
stream.Position = 0; //Not sure if this is required
return File(stream,"HelloWorld.pdf");
}
结果测试
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。