How to generate Jasper Report in HTML without writing file? - html

The code below is generating the HTML report fine on a new browser window, but it is writing the HTML file on the app server. Is there a way to generate an HTML report in Jasper without having to write the HTML file to the app server?
I can do it in PDF using JasperRunManager.runReportToPdfStream(), but there's no such method for HTML. Any ideas?
//For HTML file
String reportPath = JasperRunManager.runReportToHtmlFile(sourceFileName, parameters, conn);
File reportHtmlFile = new File(reportPath);
FileInputStream fis = new FileInputStream(reportHtmlFile);
byte[] bytes = new byte[(int)reportHtmlFile.length()];
fis.read(bytes);
response.setHeader("Content-Disposition","inline; ");
response.setContentType("text/html");
response.setContentLength(bytes.length);
servletOutputStream.write(bytes, 0, bytes.length);
servletOutputStream.flush();
servletOutputStream.close();

Related

Creating PDf consisting of multiple Pages with itext 7

i am using itext 7 to create a multi Pages PDf out of a Html file.
MemoryStream finalDocumenStream = new MemoryStream();
StampingProperties documentProperties = new StampingProperties();
documentProperties.UseAppendMode();
PdfDocument finalPDfDocument = new PdfDocument(new PdfWriter(finalDocumenStream),
documentProperties);
I am looping in an foreach over an array and call this method to create the document:
CustomTagWorkerFactory customTagWorkerFactory = new CustomTagWorkerFactory(page);
Document pDFdocument = HtmlConverter.ConvertToDocument(htmltext, new PdfWriter(stream),
converterProperties);
I want to save the Documents to finalPdfDocumet
pDFdocument.GetPdfDocument().CopyPagesTo(1,
pDFdocument.GetPdfDocument().GetNumberOfPages(), finalPDfDocument);
After foreach() iam returning the finalDocumenStream; I was expecting to get all the documents in here.
I want to return the Pdf Stream from my .Net Api Controller:
return File(pdfStream, "application/pdf");
I am not able to combine the streams of inside the iteration and return the documents to client.
What iam doing wrong? Any advises?
Thanks for your help?
First of all please be aware that PdfDocument instances created with a PdfWriter usually on one hand contain unfinished objects and on the other hand already have data written out to the PdfWriter. Thus, you cannot cleanly copy pages from them to other documents.
When you try to copy from then, usually even an exception is thrown that says so. Do you probably catch and ignore such exceptions?
Thus, to combine such documents, initially target them to a MemoryStream, close them when they are finished, and construct a new PdfDocument based on only a PdfReader initialized with that MemoryStream.
I.e.
PdfDocument fullDocument = new PdfDocument(...);
...
MemoryStream ms = new MemoryStream();
PdfDocument partialDoc = new PdfDocument(new PdfWriter(ms));
[... add content to partialDoc ...]
partialDoc.Close();
partialDoc = new PdfDocument(new PdfReader(ms.ToArray()));
partialDoc.CopyPagesTo(1, partialDoc.GetNumberOfPages(), fullDocument);
partialDoc.Close();
...
fullDocument.Close();

Send RDLC in Email as Body

I Already Digging for 5 hours but nothing to found. Is there any way to generate the rdlc into HTML. I tried RDLC to Image but my problem is, the generated image is slice in half.
Finally found solution(even though is not best answer). So basically, convert first to Excel then convert the excel into html then read all the text. I use the FreeSprite.XLS to convert the excel into html.
Freespire.xls Link
here is my code
private string GenerateHTMLReport(ReportViewer rv)
{
string mimeType,
encoding,
fileNameExtension;
Warning[] warnings=null;
string[] streamIds=null;
//Export report
byte[] exportBytes = rv.LocalReport.Render("Excel", null, out mimeType, out encoding,
out fileNameExtension, out streamIds, out warnings);
//convert to excel
FileStream fs = new FileStream("report.xls", FileMode.Create);
fs.Write(exportBytes, 0, exportBytes.Length);
fs.Close();
Workbook workbook = new Workbook();
workbook.LoadFromFile("report.xls");
//convert Excel to HTML
Worksheet sheet = workbook.Worksheets[0];
sheet.SaveToHtml("report.html");
string html =System.IO.File.ReadAllText("report.html");
return "";
}
generated HTML Code.
generated HTML in Preview.
Hopefully someone will found it helpful.

HTML from Database to PDF

I need to generate pdf from html dynamically using asp.net. HTML is stored in database. HTML has tables and css, upto 10 pages. I have tried iTextSharp by directly passing html, it produces pdf which is not opening. Destination pdf.codeplex.com has no documentation, it produces PDF with styles from parent page.
Any other solution will be helpful.
I've tried many HTML to PDF solutions including iTextSharp, wkhtmltopdf and ABCpdf (paid)
I'm currently settled on PhantomJS a headless, open-source, WebKit-based browser. It is scriptable with a javascript API which is reasonably well documented.
The only disadvantage I found was that attempting to use stdin to pass HTML into the process was unsuccessful because the REPL still has some bugs. I also found that using stdout seemed to be a lot slower than simply allowing the process to write to disk.
The code below avoids stdin and stdout by creating the javascript input as a temp file, executing PhantomJS, copying the output file to a MemoryStream and cleaning up the temporary files at the end.
using System.IO;
using System.Drawing;
using System.Diagnostics;
public Stream HTMLtoPDF (string html, Size pageSize) {
string path = "C:\\dev\\";
string inputFileName = "tmp.js";
string outputFileName = "tmp.pdf";
StringBuilder input = new StringBuilder();
input.Append("var page = require('webpage').create();");
input.Append(String.Format("page.viewportSize = {{ width: {0}, height: {1} }};", pageSize.Width, pageSize.Height));
input.Append("page.paperSize = { format: 'Letter', orientation: 'portrait', margin: '1cm' };");
input.Append("page.onLoadFinished = function() {");
input.Append(String.Format("page.render('{0}');", outputFileName));
input.Append("phantom.exit();");
input.Append("};");
// html is being passed into a string literal so make sure any double quotes are properly escaped
input.Append("page.content = \"" + html.Replace("\"", "\\\"") + "\";");
File.WriteAllText(path + inputFileName, input.ToString());
Process p;
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = path + "phantomjs.exe";
psi.Arguments = inputFileName;
psi.WorkingDirectory = Path.GetDirectoryName(psi.FileName);
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
p = Process.Start(psi);
p.WaitForExit(10000);
Stream strOut = new MemoryStream();
Stream fileStream = File.OpenRead(path + outputFileName);
fileStream.CopyTo(strOut);
fileStream.Close();
strOut.Position = 0;
File.Delete(path + inputFileName);
File.Delete(path + outputFileName);
return strOut;
}

IText html to pdf img

I am converting a html document to a pdf document and send it with java mail.
I want to insert an image on the top of the pdf document with:
<img alt="Logo" class="logo" src="https://www.somesite.org/images/logo.png"/>
But it isnt shown in the pdf document.
The link is working correctly, i tried it in my browser.
When i put in a absolute path to the image on my server he finds the path, but the email programm doesnt have access to our server of course, except of the link i want to use...
Isnt it possible to use such links?
EDIT:
final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setValidating(false);
DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
builder.setEntityResolver(FSEntityResolver.instance());
SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
String filename = wrapper.GetHtmlFilename(this.getClass().getName());
String html = wrapper.GetHtmlFile(filename, "UTF-8");
String result = wrapper.GetBody(html);
document = builder.parse(new ByteArrayInputStream(result.getBytes("UTF-8")), "UTF-8");
baos = new ByteArrayOutputStream();
renderer = new ITextRenderer();
renderer.setDocument(document, null);
renderer.layout();
renderer.createPDF(baos);

creating pdf with itextsharp with images from database

I have a process where the html is stored in database with image links. the images are also stored in db as well. I've created a controller action which reads the image from database. the path I'm generating is something like /File/Image?path=Root/test.jpg.
this image path is embedded in html in img tag like <img alt="logo" src="/File/Image?path=Root/001.jpg" />
I'm trying to use itextsharp to read the html from the database and create a pdf document
string _html = GenerateDocumentHelpers.CommissioningSheet(fleetId);
string _html = GenerateDocumentHelpers.CommissioningSheet(fleetId);
Document _document = new Document(PageSize.A4, 80, 50, 30, 65);
MemoryStream _memStream = new MemoryStream();
PdfWriter _writer = PdfWriter.GetInstance(_document, _memStream);
StringReader _reader = new StringReader(_html);
HTMLWorker _worker = new HTMLWorker(_document);
_document.Open();
_worker.Parse(_reader);
_document.Close();
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=Commissioning.pdf");
Response.ContentType = "application/pdf";
Response.Buffer = true;
Response.OutputStream.Write(_memStream.GetBuffer(), 0, _memStream.GetBuffer().Length);
Response.OutputStream.Flush();
Response.End();
return new FileStreamResult(Response.OutputStream, "application/pdf");
This code gives me an illegal character error. this comes from the image tag, it is not recognizing ? and = characters, is there a way I can render this html with img tag so that when I create a pdf it renders the html and image from the database and creates a pdf or if itextsharp can't do it, can you provide me with any other third party open source tools that can accomplish this task?
If the image source isn't a fully qualified URL including protocol then iTextSharp assumes that it is a file-based URL. The solution is to just convert all image links to absolute in the form http://YOUR_DOMAIN/File/Image?path=Root/001.jpg.
You can also set a global property on the parser that works pretty much the same as the HTML <BASE> tag:
//Create a provider collection to set various processing properties
System.Collections.Generic.Dictionary<string, object> providers = new System.Collections.Generic.Dictionary<string, object>();
//Set the image base. This will be prepended to the SRC so watch your forward slashes
providers.Add(HTMLWorker.IMG_BASEURL, "http://YOUR_DOMAIN");
//Bind the providers to the worker
worker.SetProviders(providers);
worker.Parse(reader);
Below is a full working C# 2010 WinForms app targeting iTextSharp 5.1.2.0 that shows how to use a relative image and set its base using the global provider. Everything is pretty much the same as your code, although I through in a bunch of using statements to ensure proper cleanup. Make sure to watch the leading and trailing forward slashes on everything, the base URL gets prepended directly only the SRC attribute and you might end up with double-slashes if its not done correctly. I'm hard-balling a domain in here but you should be able to easily use the System.Web.HttpContext.Current.Request object.
using System;
using System.IO;
using System.Windows.Forms;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string html = #"<img src=""/images/home_mississippi.jpg"" />";
string outputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "HtmlTest.pdf");
using (FileStream fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
using (Document doc = new Document(PageSize.TABLOID)) {
using (PdfWriter writer = PdfWriter.GetInstance(doc, fs)) {
doc.Open();
using (StringReader reader = new StringReader(html)) {
using (HTMLWorker worker = new HTMLWorker(doc)) {
//Create a provider collection to set various processing properties
System.Collections.Generic.Dictionary<string, object> providers = new System.Collections.Generic.Dictionary<string, object>();
//Set the image base. This will be prepended to the SRC so watch your forward slashes
providers.Add(HTMLWorker.IMG_BASEURL, "http://www.vendiadvertising.com");
//Bind the providers to the worker
worker.SetProviders(providers);
worker.Parse(reader);
}
}
doc.Close();
}
}
}
this.Close();
}
}
}