Hi rani,
This is happening because the JPEG does not support a transparent background. So you have to use PNG format.
Check this example. Now please take its reference and correct your code.
Namespaces
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using SautinSoft.Document;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
Controller
public class HomeController : Controller
{
private IWebHostEnvironment Environment;
public HomeController(IWebHostEnvironment _environment)
{
Environment = _environment;
}
public IActionResult Index()
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3]
{
new DataColumn("Id", typeof(string)),
new DataColumn("Name", typeof(string)),
new DataColumn("BirthDate", typeof(DateTime))
});
dt.Rows.Add(1, "Nancy Davolio", "1948-12-08");
dt.Rows.Add(2, "Andrew Fuller", "1952-02-19");
dt.Rows.Add(3, "Janet Leverling", "1963-08-30");
dt.Rows.Add(4, "Margaret Peacock", "1937-09-19");
DataTable dtChart = new DataTable();
dtChart.Columns.AddRange(new DataColumn[]
{
new DataColumn("Product", typeof(string)),
new DataColumn("Total", typeof(int))
});
dtChart.Rows.Add("Chair", 56);
dtChart.Rows.Add("Table", 69);
dtChart.Rows.Add("Stool", 5);
ViewBag.Product = string.Join(",", dtChart.AsEnumerable().Select(r => r.Field<string>("Product")).ToArray());
ViewBag.Total = string.Join(",", dtChart.AsEnumerable().Select(r => r.Field<int>("Total")).ToArray());
return View(dt);
}
[HttpPost]
public FileResult PDF(string hfHTML, string hfChartData)
{
string html = GetHTML(hfHTML, hfChartData);
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
using (MemoryStream stream = new MemoryStream())
{
StringReader sr = new StringReader(html);
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, stream);
pdfDoc.Open();
XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr);
pdfDoc.Close();
return File(stream.ToArray(), "application/pdf", "Grid.pdf");
}
}
[HttpPost]
public FileResult Word(string hfHTML, string hfChartData)
{
string html = GetHTML(hfHTML, hfChartData);
string path = Path.Combine(this.Environment.WebRootPath, "Files");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string input = Path.Combine(path, "html1.html");
string output = Path.Combine(path, "Grid.docx");
System.IO.File.WriteAllText(input, html);
DocumentCore documentCore = DocumentCore.Load(input);
documentCore.Save(output);
byte[] bytes = System.IO.File.ReadAllBytes(output);
Directory.Delete(path, true);
return File(bytes, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "Grid.docx");
}
[HttpPost]
public FileResult Excel(string hfHTML, string hfChartData)
{
string html = GetHTML(hfHTML, hfChartData);
return File(Encoding.ASCII.GetBytes(html), "application/vnd.ms-excel", "Grid.xls");
}
private string GetHTML(string table, string image)
{
byte[] bytesImage = Convert.FromBase64String(image.Replace("data:image/png;base64,", ""));
string path = Path.Combine(this.Environment.WebRootPath, "Uploads");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
System.IO.File.WriteAllBytes(path + "\\Chart.jpg", bytesImage);
return string.Format("{0}<div> </div><img src='{1}' height='300' width='400' />", table, path + "\\Chart.jpg");
}
}
View
@model System.Data.DataTable
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/select/1.3.3/js/dataTables.select.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/datetime/1.0.2/js/dataTables.dateTime.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.24/css/jquery.dataTables.min.css" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/select/1.3.3/css/select.dataTables.min.css" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/datetime/1.0.2/css/dataTables.dateTime.min.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js"></script>
<script type="text/javascript">
$.fn.dataTable.render.moment = function (from, to, locale) {
// Argument shifting
if (arguments.length === 1) {
locale = 'en';
to = from;
from = 'DD-MM-YYYY';
}
else if (arguments.length === 2) {
locale = 'en';
}
return function (d, type, row) {
if (!d) {
return type === 'sort' || type === 'type' ? 0 : d;
}
var m = window.moment(d, from, locale, false);
return m.format(type === 'sort' || type === 'type' ? 'x' : to);
};
};
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
};
function PopulateChart() {
var labels = '@ViewBag.Product';
var datas = '@ViewBag.Total';
var labelsArray = new Array();
var dataArray = new Array();
var colorArray = new Array();
for (var i = 0; i < labels.split(',').length; i++) {
labelsArray.push(labels.split(',')[i]);
dataArray.push(datas.split(',')[i]);
colorArray.push(getRandomColor());
}
new Chart(document.getElementById("chart").getContext('2d'), {
type: 'pie',
data: {
labels: labelsArray,
datasets: [{
backgroundColor: colorArray,
data: dataArray
}]
}
});
};
$(function () {
$("#myTable").dataTable({
bLengthChange: true,
lengthMenu: [[10, 25, 50, 100], [10, 25, 50, 100]],
bFilter: true,
bSort: true,
bPaginate: true,
columns: [
{ data: 'Id' },
{ data: 'Name' },
{ data: 'BirthDate', render: $.fn.dataTable.render.moment('MM/DD/YYYY') }
],
});
PopulateChart();
$('.download').click(function () {
var imgData = $('#chart')[0].toDataURL("image/png", 1.0);
$('input[name=hfHTML]').val($('#myTable')[0].outerHTML);
$('input[name=hfChartData]').val( imgData);
});
});
</script>
</head>
<body>
<form asp-controller="Home" method="post">
<input type="hidden" name="hfHTML" value="" />
<input type="hidden" name="hfChartData" value="" />
<button class="download" type="submit" asp-action="Excel">Excel</button>
<button class="download" type="submit" asp-action="Word">Word</button>
<button class="download" type="submit" asp-action="PDF">PDF</button>
</form>
<hr />
<section class="content">
<div class="container-fluid">
<table class="table table-bordered table-responsive-lg table-hover" width="100%" id="myTable">
<thead class="thead-dark text-center">
<tr>
<th>Id</th>
<th>Name</th>
<th>Date</th>
</tr>
</thead>
<tbody class="text-center">
@for (int i = 0; i < Model.Rows.Count; i++)
{
<tr>
<td>@Model.Rows[i]["Id"]</td>
<td>@Model.Rows[i]["Name"]</td>
<td>@Convert.ToDateTime(Model.Rows[i]["BirthDate"]).ToString("dd/MM/yyyy")</td>
</tr>
}
</tbody>
</table>
</div>
</section>
<div class="box-body">
<div class="chart-container">
<canvas id="chart" style="width:50%; height:50%"></canvas>
</div>
</div>
</body>
</html>