Does anybody know how to make a print page button print a pdf document?
At the moment i'm using
Print Page
Obviously that just prints the page though. I have had to create pdf's for each page and thought it would be easier just to print the pdf instead of the page (Cross browser printing styles is kinda sucking ;).
Any ideas?
There is no standard way to print anything in PDF in any browser, such as on the Windows platform. On the Mac, there is always an option to print something as a PDF file, so regular printing will do.
I suggest you use Itextsharp. If you are using asp.net c#, this code works for you. Runs in the server side though. You can just put the html inside a panel to make it readable in the server.
/// import these namespaces
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
using System.Web.Services;
using System.Text;
/// Call this method whenever you need to convert
/// the html content inside the panel which runs in the server side.
[WebMethod]
public void ConvertHtmlStringToPDF()
{
StringBuilder sb = new StringBuilder();
StringWriter tw = new StringWriter(sb);
HtmlTextWriter hw = new HtmlTextWriter(tw);
pnlPDF.RenderControl(hw);
string htmlDisplayText = sb.ToString();
Document document = new Document();
MemoryStream ms = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(document, ms);
StringReader se = new StringReader(htmlDisplayText);
HTMLWorker obj = new HTMLWorker(document);
document.Open();
obj.Parse(se);
// step 5: we close the document
document.Close();
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=report.pdf");
Response.ContentType = "application/pdf";
Response.Buffer = true;
Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
Response.OutputStream.Flush();
Response.End();
}
Related
Is it possible to save a rendered view as html file?
I need to save a view as an "Testfile.html" after Razor and javascript has rendered. Is it possible?
What i am trying to do, is take the saved view, that includes canvas created using chart.js, and save them as an html file. Afterwards i want to convert the html file to a pdf using iText7
Take a look on the below code :
First of all there is no need to save the HTML as a physical file, you can just call the razor engine renderer from within your controller, for example, so as to return the final string response.
public string RenderRazorViewToString(string viewName, object model)
{
ViewData.Model = model;
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}
Then you can pass this response to your exporter so that it can return to you the pdf file, that you will later on return directly to the client
string htmlContent = RenderRazorViewToString("SomeViewDefinedAsPartial", ReportModel);
//// fetch view's pdf styles
string CSSContent = "";
var byteRslt = PDFExporter.ConvertToPDF(htmlContent, CSSContent);
Important: HTML to PDF renderers usually dont play well enough with dynamic pages that require javascript to do initializations, but i hope this answer will help you move forwards in your requirement/implementation.
You can directly convert the View to pdf file using wkhtmltopdf
wkhtmltopdf need to be installed on the server and its path is used in the web.config from here the c# code will use this path and convert it to pdf file.
i have code for printing normal piecharts using iTextSharp.dll (pdf generating lib)
namespaces used:
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using System.Web.UI.DataVisualization.Charting;
code:
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
using (MemoryStream stream = new MemoryStream())
{
PieChart1.SaveImage(stream, ChartImageFormat.Png); //error line
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=Chart.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
Response.End();
}
But this code dosen't work for ajax pie charts, it show error:
Error 1 'AjaxControlToolkit.PieChart' does not contain a definition for 'SaveImage' and no extension method 'SaveImage' accepting a first argument of type 'AjaxControlToolkit.PieChart' could be found (are you missing a using directive or an assembly reference?)
also is there any other way like printing piechart's div from javascript?
or any other code sample/reference?
if you want to perform action from javascript. i would suggest you to use Highcharts it is best for all types of charts and also it gives builtin print and download as image or PDF.
http://www.highcharts.com/demo/pie-basic
check this link and demo it is user friendly and light weight.
Hi I have a defined variable contentAll from where I am writing to server as a PDF and mailing it to users. They want to see it open in a browser.
Server C# code is as below
List<int> contentAll = new List<int>();
contentAll = [01,02, 03,.....] etc. - Just a sample
byte[] base64EncodedStringBytes = Encoding.ASCII.GetBytes(Convert.ToBase64String(contentAll.SelectMany<int, byte>(BitConverter.GetBytes).ToArray()));
return Ok(base64EncodedStringBytes);
Jquery Code is as below
var pdfWin = window.open("data:application/pdf;base64," + response, "_blank", 'height=650,width=840');
Where response is the returned base64EncodedStringBytes
I am able to write the PDF and send it so no issues with content.
However Chrome is not opening it. The Error in PDF window . Can someone assist
I want to take the screenshot of Jsp page in the browser. I had googled a lot. Everyone is pointing to java.awt.Robot functionality. It is great. But what i need is i want the screenshot of the full web page which is also inside the scrollable area of the browser window. Moreover i want only the webpage content not the status bar and other tabs and menus on the browser. I had used the following code.
public class ScreenCapture {
public void TakeCapture()
{
try
{
Robot robot = new Robot();
String format = "jpg";
String fileName = "D:\\PDFTest\\PartialScreenshot." + format;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle captureRect = new Rectangle(0, 0, screenSize.width , screenSize.height);
BufferedImage screenFullImage = robot.createScreenCapture(captureRect);
ImageIO.write(screenFullImage, format, new File(fileName));
Document document = new Document();
String input = "D:\\PDFTest\\PartialScreenshot.jpg";
String output = "D:\\PDFTest\\PartialScreenshot.pdf";
try {
FileOutputStream fos = new FileOutputStream(output);
PdfWriter writer = PdfWriter.getInstance(document, fos);
writer.open();
document.open();
document.add(Image.getInstance(input));
document.close();
writer.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
catch (AWTException | IOException ex) {
System.err.println(ex);
}
}
public String getTakeCapture() {
return getTakeCapture();
}
Is there a way to take the screen shot of the full JSP webpage that is viewing in the browser.(Along the content inside the scrollable window) and then I have to convert this screenshot into PDF. Don't tell me the ways to directly convert it into the PDF using FlyingSaucer as it's not working in my case.
This is not possible in pure Java.
However you can add the html2canvas library to your JSP page. You can then use Javascript to submit the canvas image to your servlet and process it as you please.
See the following question and answer that deals with similar problem: How to upload a screenshot using html2canvas?
My Goal is to print a RDLC report on the client machine without preview. I can not use the ReportViewer print button since it requires the installation of ActiveX object and there are no permissions for that. So, I'm using ITextSharp to create a PDF from the byte array returned from the rendered LocalReport, and add a JavaScript for print.
During Debug, I can see that the PDF is generated and has 2 pages, and everything looks OK. I don't receive any errors and the function exits OK, but it doesn't print. What am I doing wrong, or what am I missing?
This is my code:
string jsPrint = "var pp = this.getPrintParams();pp.interactive= pp.constants.interactionLevel.silent;this.print(pp);";
byte[] bytes = report.Render("PDF", null, out mimeType, out encoding, out extension, out streamids, out warnings);
using (MemoryStream ms = new MemoryStream())
{
Document doc = new Document();
PdfWriter writer = PdfWriter.GetInstance(doc, ms);
doc.SetPageSize(PageSize.A4);
doc.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage page;
PdfReader reader = new PdfReader(bytes);
int pages = reader.NumberOfPages;
for (int i = 1; i <= pages; i++)
{
doc.SetPageSize(PageSize.A4);
doc.NewPage();
page = writer.GetImportedPage(reader, i);
cb.AddTemplate(page, 0, 0);
}
PdfAction jAction = PdfAction.JavaScript(jsPrint, writer);
writer.AddJavaScript(jAction);
doc.Close();
}
Thanks.
Regarding your question about PdfStamper (in the comments). It should be as simple as this:
string jsPrint = "var pp = this.getPrintParams();pp.interactive= pp.constants.interactionLevel.silent;this.print(pp);";
PdfReader reader = new PdfReader(bytes);
MemoryStream stream = new MemoryStream();
PdfStamper stamper = new PdfStamper(pdfReader, stream);
stamper.Writer.AddJavaScript(jsPrint);
stamper.Close();
reader.Close();
Regarding your original question: automatic printing of PDF documents is considered being a security hazard: one could send a PDF to an end-user and that PDF would cause the printer to spew out pages. That used to be possible with (really) old PDF viewers, but modern viewers prevent this from happening.
In other words: you may be trying to meet a requirement of the past. Today's PDF viewers always require an action from the end user to print a PDF document.