Hi Aspose,
I’m try to generate pdf using html string.
I saved the generated pdf into memory stream and wanted to load it in browser.
I can see the genreted pdf in browser but having an issue when I try to download it from chrome browser. (it is working fine in firefox).
I would like to know is there anything missing in my code.?
Here my code
private void GeneratePDF()
{
var htmlString = @"D:/test.html";
var meidaFilePath = @"D:/img";
if (string.IsNullOrEmpty(htmlString))
{
Context.Response.End();
return;
}
var now = DateTime.Now;
var fileName = string.Format("{0}-{1}.pdf", "My-Sample", now.ToString("yyyyMMddHHmmss"));
var bytes = GetPdfFromHtml(htmlString, meidaFilePath, fileName);
Context.Response.Buffer = true;
Context.Response.AddHeader("content-length", bytes.Length.ToString());
Context.Response.AddHeader("Content-Disposition", string.Format("inline;filename={0}", "iresha.pdf"));
Context.Response.ContentType = "application/pdf";
Context.Response.BinaryWrite(bytes);
Context.Response.Flush();
Context.Response.End();
}
public static byte[] GetPdfFromHtml(string html, string mediaPath, string fileName)
{
// Get the license
var asposeLicenseFileName = ConfigurationManager.AppSettings["AsposeLicPath"];
if (!string.IsNullOrEmpty(asposeLicenseFileName))
{
try
{
// instantiate the license class
var license = new AsposeLicense();
//pass only the name of the license file embedded in the assembly
license.SetLicense(asposeLicenseFileName);
}
catch (Exception ex)
{
// run as evaluation if this fails
NLogManager.LogGeneralError("Aspose Error",
"Could not load Aspose licence file. Please check the correct Aspose licence file : " + asposeLicenseFileName,
ex.Message);
}
}
var objLoadOptions = new HtmlLoadOptions(mediaPath);
objLoadOptions.PageInfo.Margin.Bottom = 10;
objLoadOptions.PageInfo.Margin.Top = 30;
objLoadOptions.PageInfo.Margin.Left = 10;
objLoadOptions.PageInfo.Margin.Right = 10;
var doc = new Document(new MemoryStream(Encoding.UTF8.GetBytes(html)), objLoadOptions);
doc.Info.Title = fileName;
var emptyPageNumbers = new List<int>();
for (var pageNo = 1; pageNo <= doc.Pages.Count;)
{
if (doc.Pages[pageNo].IsBlank(0.01d))
{
emptyPageNumbers.Add(pageNo);
}
pageNo++;
}
if (emptyPageNumbers.Count > 0)
{
//Remove Empty Pages
doc.Pages.Delete(emptyPageNumbers.ToArray());
}
// Return bytes
using (var ms = new MemoryStream())
{
doc.Save(ms, SaveFormat.Pdf);
return ms.ToArray();
}
}