Print a PDF Document Programmatically - asp.net

How can i Print a Pdf document through programmatically?
i am using the follwing code to print a PDF file.but when i click on print icon directly it starts printing.but i dont want it.
<asp:ImageButton ID="PrintButton" runat="server" ImageUrl="~/images/print-icon.png"
OnClick="PrintButton_Click" ToolTip="Print Document" />
My Cs Code is
protected void PrintButton_Click(object sender, EventArgs e)
{
ProcessStartInfo infoPrint = new ProcessStartInfo();
infoPrint.FileName = Session["filename"].ToString();
infoPrint.Verb = "PrintTo";
infoPrint.CreateNoWindow = true;
infoPrint.WindowStyle = ProcessWindowStyle.Normal;
infoPrint.UseShellExecute = true;
Process printProcess = new Process();
printProcess = Process.Start(infoPrint);
}
i want to open a print dialog box when the user clicks on print icon.if the user clicks on Print Button in Print dialog box then i want to start printing the document. My PDF file is in a folder on the server i want it to be printed through programmatically in asp.net.

this code will run on the server not the client. while developing the server and client are the same machine, your local workstation. Once deployed, this would execute on the server, not the user's local work station.
you can open a print dialog box using javascript
window.print();
However that will print the entire webapge, not the document specifically.
If you would like to print only the PDF, you need to stream the file to browser (not an entire webform). The user can then take advantage of the native print options within the adobe reader. There are many examples online about how to stream documents to the client's browser.

Have a look at This posst
this code add javascript line to print the pdf
Public Shared Function PrintJStoPDF(thePDF As Byte(), direct As Boolean) As Byte()
Dim BB As Byte() = Nothing
Using ms As New MemoryStream
Using reader As New PdfReader(thePDF)
Dim stamper = New PdfStamper(reader, ms)
Dim jsText As String = "var res = app.setTimeOut('this.print({bUI: true, bSilent: " & direct.ToString.ToLower & ", bShrinkToFit: false});', 200);"
stamper.JavaScript = jsText
stamper.FormFlattening = True
stamper.Writer.CloseStream = False
stamper.Close()
ms.Position = 0
BB = ms.ToArray
End Using
End Using
Return BB
End Function

Related

ASP.NET - How to redirect a response with a PDF to a new tab?

I have a method which I call directly from the Page_Load method, to create a PDF and print it, using PdfSharp, which is called like this:}
if(IsPostBack)
PdfSharpConvert(eventArgument, Response);
And the method looks like this:
public static void PdfSharpConvert(String html, System.Web.HttpResponse response)
{
Bitmap bitmap = new Bitmap(790, 1800);
Graphics g = Graphics.FromImage(bitmap);
XGraphics xg = XGraphics.FromGraphics(g, new XSize(bitmap.Width, bitmap.Height));
TheArtOfDev.HtmlRenderer.PdfSharp.HtmlContainer c = new TheArtOfDev.HtmlRenderer.PdfSharp.HtmlContainer();
c.SetHtml(html);
PdfDocument pdf = new PdfDocument();
PdfPage page1 = new PdfPage();
... code to paint the page ...
MemoryStream stream = new MemoryStream();
pdf.Save(stream, false);
response.Clear();
response.ContentType = "application/pdf";
response.AddHeader("content-length", stream.Length.ToString());
response.BinaryWrite(stream.ToArray());
response.Flush();
stream.Close();
response.End();
}
This works fine, I get the PDF viewer on the browser, but I'm trying to show the PDF in a different tab in the browser, not on the same one, is there a way to do this without rewriting the views I use or doing something more complicated? I tried using response.Redirect, and it does redirect, but I don't know what to give it as a parameter so it properly shows the PDF in a different page.
You require a client side javascript button.
You need to set session, or even pass the file name as part of the url.
so, say like this:
window.open('MyPdfViewer.aspsx', '_blank;);
or maybe:
window.open('MyPdfViewer.aspsx?FileName=' + MyFileName, '_blank;);
Then in the on-page load of MyPdfViewer, in the is-post back = false code stub, you place your code to pump out the pdf.
So, that 2nd new tab and web page? The on-load event of that page will have to fetch the pdf file, and push it out as you are doing now.
So pass the file name in the URL, or assume session[] has the file name to display.
You can also consider display on the current page - inside of a iFrame.

Export Crystal Report to PDF in a Loop only works with first

i'm trying to generate a report and export it to pdf in a loop, the report will receive a new parameter in each loop and prompt the client to download a PDF, in other words, the client may need to download 2 or 3 (or more) PDFs at the same time, the problem is that the prompt to accept the download only appears for the first pdf, dont know why. I can export to disk (server side) without any problems.
Code:
Sub PrintReport(ByVal Cod As Integer)
Dim CTableLogInfo As TableLogOnInfo
Dim ConnInfo As CrystalDecisions.Shared.ConnectionInfo = New ConnectionInfo()
ConnInfo.Type = ConnectionInfoType.SQL
ConnInfo.ServerName = ConfigurationManager.AppSettings("SQLSERVERNAME")
ConnInfo.DatabaseName = ConfigurationManager.AppSettings("SQLDBNAME")
ConnInfo.UserID = ConfigurationManager.AppSettings("SQLSERVERUSER")
ConnInfo.Password = ConfigurationManager.AppSettings("SQLSERVERPASSWORD")
ConnInfo.AllowCustomConnection = False
ConnInfo.IntegratedSecurity = False
For Each CTable As Table In CrystalReportSource1.ReportDocument.Database.Tables
CTable.LogOnInfo.ConnectionInfo = ConnInfo
CTableLogInfo = CTable.LogOnInfo
CTableLogInfo.ReportName = CrystalReportSource1.ReportDocument.Name
CTableLogInfo.TableName = CTable.Name
CTable.ApplyLogOnInfo(CTableLogInfo)
Next
Dim pField As ParameterField = CrystalReportSource1.ReportDocument.ParameterFields(0)
Dim val1 As ParameterDiscreteValue = New ParameterDiscreteValue
val1.Value = Cod
pField.CurrentValues.Clear()
pField.CurrentValues.Add(val1)
Dim PDFName As String = "PDF Nº " & Cod
CrystalReportSource1.ReportDocument.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Page.Response, True, PDFName)
End Sub
EDIT:
Tried to zip the reports with DotNetZip but i get an broken zip.
Can you tell me whats wrong? (Solved: code bellow is corrected now)
Response.ClearContent()
Response.ClearHeaders()
Response.ContentType = "application/zip"
Response.AppendHeader("content-disposition", "attachment; filename=AllPDFs.zip")
Using zipFile As New ZipFile()
For i = 0 To Cod.Length - 1
If Cod(i) > 0 Then
val1.Value = Cod(i)
pField.CurrentValues.Clear()
pField.CurrentValues.Add(val1)
val2.Value = Cod(i)
pField2.CurrentValues.Clear()
pField2.CurrentValues.Add(val2)
Dim PDFNameAs String = "PDF Nº " & Cod(i) & ".pdf"
Dim s As New System.IO.MemoryStream
s =CrystalReportSource1.ReportDocument.ExportToStream(ExportFormatType.PortableDocFormat)
zipFile.AddEntry(PDFName, s)
End If
Next
zipFile.Save(Response.OutputStream)
End Using
Response.Clear()
Probably the response ends after the first one, therefore there's no response to write to for the 2nd and 3rd attempts.
Instead, you can have the client download the reports via AJAX Request (move your report generation into an .ashx generic handler), or have the user click the button 3 times to initiate new requests.
Or zip the PDF's up until a single file and allow the client to download that.

Getting a dynamically created PDF from a URL

I have a need to aquire a pdf file generated from an aspx site.
Backstory:
I want to get schedueles from a website, I have succeded in getting the url to the scheduele, containing parameters. If you follow the url you will be shown a PDF stream, created by the site using given parameters.
http://www.novasoftware.se/ImgGen/schedulegenerator.aspx?format=pdf&schoolid=57240/sv-se&type=1&id=%7bD8920398-FA90-4960-BD47-69A8EFF7204D%7d&period=&week=38&mode=0&printer=1&colors=2&head=1&clock=1&foot=1&day=0&width=2480&height=3507&count=1&decrypt=0
This URL is what the site uses to get the appropriate scheduele and display it as a pdf.
Since it's not theoretically a PDF file, I can't download it as one using:
Dim Downloader As New WebClient
Downloader.DownloadFile(URL, fileName)
Neither can i download the content as a string using...
Dim Downloader As New WebClient
Dim Result As String = Downloader.DownloadString(URL)
...since it will result in an 500 Server Error due to missing parameters.
The only way of displaying the file/stream/document or whatever it's real name is, is to visit the given url through a browser. Given that, I tried to grab the PDF through a WebBrowser control. But since it "Can't display the XML page" (error displayed when navigating to the scheduele URL) I can't use that approach either.
So my question is, How do I download this data as a PDF or How do I get this data as a Stream that i can read with StreamReader?
Sidenotes:
The page uses no further client-side connections so I cannot backtrack it.
(I used Fiddler2 to track all the connections)
Using Fiddler, I can tell that the url SomethingSomething.com/Something.aspx generates a PDF and displays it. First few lines of the generated document (through Fiddler)
%PDF-1.4
%����
%
%wPDF by WPCubed GmbH V3.54x[0]
%
%
1 0 obj
<>
There are more information I can get from Fiddler about this site, so if you need it either try it yourself or ask me to add the information here.
Use the code below to download the file to memory stream:
Dim webRes As HttpWebResponse = Nothing
Dim memStream As New MemoryStream
Try
Dim webReq As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest)
webReq.Credentials = CredentialCache.DefaultCredentials
webRes = webReq.GetResponse
Dim resStream As Stream = webRes.GetResponseStream
Dim bytesRead As Integer
Do
Dim buffer(1023) As Byte
bytesRead = resStream.Read(buffer, 0, buffer.Length)
memStream.Write(buffer, 0, bytesRead)
Loop Until bytesRead = 0
Catch ex As Exception
Finally
If webRes IsNot Nothing Then
webRes.Close()
webRes = Nothing
End If
memStream.Seek(0, SeekOrigin.Begin)
End Try
' optionally save the stream into a file
memStream.WriteTo(New FileStream("d:\filename.pdf", FileMode.Create))

how to call page which creates pdf

I have a page called OrderExport.aspx which creates a pdf file in a folder on the server.
In my page OrderSend.aspx I have a function which sends an e-mail with the pdf file attached, like this:
Dim atc As Net.Mail.Attachment = New Attachment(stm, fileNameOrder)
mail.Attachments.Add(atc)
How can I call OrderExport.aspx from this function before sending the e-mail without showing it for the user?
I need to make sure that the pdf file exists when sending the e-mail.
You probably want to create a class rather than an aspx page to handle the PDF creation. One way to do this is to use the PDFSharp library which can handle creating the PDF document and then saving it to a stream which can be attach to an email message. You could also save the stream to a file on the server at the same time.
' Create a new PDF document
Dim document As PdfDocument = New PdfDocument
document.Info.Title = "TITLE"
Dim securitySettings As Security.PdfSecuritySettings = document.SecuritySettings
' Restrict some rights.
securitySettings.PermitAccessibilityExtractContent = False
securitySettings.PermitAnnotations = False
securitySettings.PermitAssembleDocument = False
securitySettings.PermitExtractContent = False
securitySettings.PermitFullQualityPrint = True
securitySettings.PermitModifyDocument = False
securitySettings.PermitPrint = True
' Create an empty page
Dim page As PdfPage = document.AddPage
' Get an XGraphics object for drawing
Dim gfx As XGraphics = XGraphics.FromPdfPage(page)
Dim img As XImage = XImage.FromGdiPlusImage(imgPermit)
gfx.DrawImage(img, 20, 20)
Dim stream As New MemoryStream()
document.Save(stream, False)
Dim xStream As System.IO.Stream = stream
SendEmail(sEmail, xStream)
in your mail message it would be constructed similar to this
Dim xStream As New Attachment(pdf, "FILE" + Date.Now.ToString("MM.dd.yyyy") + ".pdf")
mm.Attachments.Add(xStream)
You need to separate the GUI from the actual logic.
You presumably have code in OrderExport.aspx that creates the PDF and saves it to disk. You should put that code into a separate class, so that you can call it from OrderExport.aspx, and from the page with the "Send e-mail" button. Similarly, extract the code for sending the email from OrderSend.aspx and call it from there, and from the "Send e-mail" button.
Separation of Concerns is the best solution, but if you need a quick solution -not a good one- make the class and the function public and call it like any other class

Crystal Report print functionlity doesn't work after deployment?

I'm using crystal reports to build reports, everything is ok while development.
But after deployment of website, print functionality doesn't work.
I use _rptDocument.PrintToPrinter(1, false, 0, 0); to print report.
I've tried two methods to deploy website
Normal Publish option.
Web Deployment Project.
But I got the same output, print functionality doesn't work.
Also, I tried to set default printer, this also doesn't work.
Any ideas?
Printing on a web server isn`t a good idea. What should happen? A user prints on your servers printer? Use CR to create PDFs. Stream them to your clients. They can use their local printers.
try this :- Create PDF and open Browser Tab ...enter code here
string fname = "Report" + ".pdf";`enter code here`
//Create instance for crystal report Export option class
ExportOptions exprtopt = default(ExportOptions);
//create instance for destination option - This one is used to set path of your pdf file save
DiskFileDestinationOptions destiopt = new DiskFileDestinationOptions();
//Bind data in the crystal report first before export cystal report to PDF
ReportDocument RptDoc = new ReportDocument();
//Map your crystal report path
// RD.Load(Server.MapPath("~/CrystalReport2.rpt"));
//Set your crystal report datasource as dt
//Get path and assign into destination DiskFileName
destiopt.DiskFileName = Server.MapPath(fname);
exprtopt = RD.ExportOptions;
exprtopt.ExportDestinationType = ExportDestinationType.DiskFile;
//use PortableDocFormat for PDF data
exprtopt.ExportFormatType = ExportFormatType.PortableDocFormat;
exprtopt.DestinationOptions = destiopt;
//finally export your report document
RD.Export();
//To open your PDF after save it from crystal report
string Path = Server.MapPath(fname);
//create instance to client to open your pdf
WebClient client = new WebClient();
//Assign path to download pdf
Byte[] buffer = client.DownloadData(Path);
//metion content type as PDF and write
// Response.ContentType = "application/pdf";
//Response.AddHeader("content-length", buffer.Length.ToString());
//Response.BinaryWrite(buffer);
//======================================
Response.Write("<script>");
Response.Write("window.open('" + fname + "', '_newtab');");
Response.Write("</script>");
//===================================
IMTIYAZ

Resources