WPF : render report in PDF format - wpf

I am working with WPF rdlc , currently I am using windowformhost reportviewer to show my report . If I need to view in PDF form I will export to PDF through the report viewer by clicking the export button .
Is that anyway to show the report directly in a PDF form instead of doing all the steps above ?
I am using VS2013 as development tools
Thank you

Yes it's possible. You want to first use the ReportViewer to render the report, then stream it to file. Once it's written to file, you can open the pdf from the file system.
Export is something along these lines:
byte[] renderedBytes = rptViewer.LocalReport.Render(
"PDF",
"<DeviceInfo><ExpandContent>True</ExpandContent></DeviceInfo>",
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);
using (FileStream fsExport = new FileStream(#"C:\MyLocation\MyReport.pdf", FileMode.Create))
{
fsExport.Write(wordbytes, 0, wordbytes.Length);
}
Now you simply open up the pdf file:
System.Diagnostics.Process.Start(#"C:\MyLocation\MyReport.pdf")

Related

Could you use Microsoft Print to PDF printer to convert an XPS to a PDF file?

I am trying to use the Microsoft Print to PDF printer to convert an XPS to a PDF.
I Tried converting my XPS Files via commandline with GhostReader and also tried to use PdfSharp.Xps. Both of these were too slow, Taking more then 30 seconds for a 10 page XPS file. Now my question is if it is possible to set an input and output File/Path for printing when i use Microsoft print to PDF
string fileGuid = Guid.NewGuid().ToString();
string xpsFile = System.IO.Path.Combine(System.IO.Path.GetTempPath(), $"{fileGuid}.Print.xps");
string pdfFile = System.IO.Path.Combine(System.IO.Path.GetTempPath(), $"{fileGuid}.Print.pdf");
PrintDocument doc = new PrintDocument()
{
DocumentName = xpsFile,
PrinterSettings = new PrinterSettings()
{
PrinterName = "Microsoft Print to PDF",
PrintToFile = true,
PrintFileName = pdfFile,
}
};
doc.Print();
This is what i have tried. But this creates an empty .PDF file that i can't use
You can check out the LEADTOOLS SDK (disclaimer: I am an employee of this vendor) which actually supports loading and saving XPS files in C# so you do not need to use a printer to do the conversion, you can simply do it directly in your application: https://www.leadtools.com/sdk/formats#document
So you could use the toolkit to simply load an XPS and save it out as a PDF quite easily with the following code and nuget package:
Install-Package Leadtools.Document.Sdk -Version 21.0.0.2
using (DocumentConverter documentConverter = new DocumentConverter())
{
documentConverter.SetDocumentWriterInstance(new DocumentWriter();
foreach (var filename in inputFiles)
{
var jobData = new DocumentConverterJobData();
jobData.InputDocumentFileName = "input.xps";
jobData.DocumentFormat = DocumentFormat.Pdf;
jobData.OutputDocumentFileName = "output.pdf");
var job = documentConverter.Jobs.CreateJob(jobData);
documentConverter.Jobs.RunJobAsync(job);
}
}
Here is a complete tutorial on how to achieve this here: https://test.leadtools.com/help/sdk/v21/tutorials/documents/cross-platform/dotnet-core/convert-files-with-the-document-converter.html
If you would rather use a printer to do the functionality, there is the Virtual Printer Driver that supports the XPS -> PDF conversion as well:
https://www.leadtools.com/help/sdk/v21/tutorials/virtual-printer/windows/dotnet/print-to-file-using-the-virtual-printer-driver.html

How to show an image from an image inputstream in Birt?

I am using birt to develop some reports,I want to display some pie charts in the birt pdf report,I found the birt chart function is not very flexiable,so I want to use jfreechart to generate an image and show it in the report instead. Now I have a question: can we show image in birt with the image inputstream,so that the image do not need to be generated and store in some place?
I know I can generate the image into a jpg file and store it in some place ,then I can access it birt report via the location of this image file.But if I do as that ,each time when we view the birt report ,it will generate a new image file,I do not want to generate so much files.
Any good ideas?
There are two possible solutions.
As you said, you can save the charts as files.
I do this in a report where I generate dozens of control charts (German: "Regelkarten"). To tidy up after the report has finished, I add the generated file names to a list, then I delete the files in the list in the report's afterRender script like this.
var images = vars["images"];
for (var i=0; i<images.size(); i++) {
var fname = images.get(i);
if (new java.io.File(fname)['delete']()) {
log.debug("Temp. image file removed: " + fname);
} else {
log.error("Could not delete temp. image file " + fname);
}
}
Note: This is OK for generating PDF or Word, but probably it wouldn't work for HTML.
In my case, I did this because I could check the generated charts outside of BIRT by just commenting out the clean up routine.
The other option is to generate a byte[]. BIRT complains in the log file then (Rhino, something about unknown type mapping Java<->Javascript), but it works.
I never have used this with JFreeChart, but that's how we do it for generating DataMatrix ("2D-Barcode") with an ancient commercial Java library from a company called "ID Automation".
The image item references row["dataMatrix_AuftID"], which is defined as type: Java Object, expression: barcode.dataMatrix(row["AUFT_ID"],70,70,80,0.03)
The function barcode.dataMatrix in our Javascript wrapper library for the Java library calls the Java library. Its last few lines look like this, which should give you an idea for your case:
var image = new java.awt.image.BufferedImage(siz.width, siz.height, t);
// get graphic context of image
var imgGraphics = image.createGraphics();
// paint DataMatrix in graphics context of image
bc.paint(imgGraphics);
// get the image's bytes in PNG format
var baos = new java.io.ByteArrayOutputStream();
javax.imageio.ImageIO.write(image, "png", baos);
var bytes = baos.toByteArray();
return bytes;
As a side-note, for a proof of concept I showed that it is also possible to generate SVG in memory and use it with BIRT. Never used this in production, however.

Unable to Download csv file using werbdriver + java

I need to downlond csv file from my application. In my application there is table which contains rows and on right click of that row it display download option , on click on of that download it displays windows popup with open and save button.
To download csv from my application i have written below code but which is not working :(
WebDriver driver;
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("browser.download.dir", "c:\\test");
profile.setPreference("browser.download.folderList", 2);
profile.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv");
profile.setPreference("browser.download.useDownloadDir", false);
profile.setPreference("browser.download.manager.showWhenStarting", false);
driver = new FirefoxDriver(profile);
driver.get("Application link");
// Steps to click on Download file
Please Help.![enter image description here][1]
Try adding
profile.setPreference("browser.download.downloadDir", "c:\\test");
profile.setPreference("browser.download.defaultFolder", "c:\\test");
In addition - csv can come in many content types, not just text/csv..
Try using Firefox addon like HTTP headers to see the exact type the response.

Converting byte[] of a PDF file original source to MemoryStream for loading into PDF viewer? (component one)

I'm working with a ComponentOne (C1) silverlight PDF viewer control.
It has a "LoadDocument" method that accepts a "Stream".
I'm making an HTTP get call from my client app to get a PDF document.
This document, on the server side, has been streamed in through File.ReadAllBytes(), then converted to a base64 string using Convert.ToBase64String().
This string is sent across the wire back to my silverlight app where it's then reversely converted back into a byte array with Convert.FromBase64String(val).
Then I'm creating a MemoryStream with that byte array and passing "LoadDocument()" that memory stream.
The viewer is rendering nothing. It shows the toolbar and scrollbars, but the contents are blank and the save button is grayed out, suggesting that no document loaded.
I know for certain the file made it across because the byte array size on the client matches teh byte array pre-conversion on the server side.
Here's my code: (in the interest of time/space, i've truncated, removing validation, etc.)
SERVERSIDE
string sendingToClient = Convert.ToBase64String(File.ReadAllBytes(filePath))
CLIENTSIDE
byte[] image = null;
image = Convert.FromBase64String(stringFromServerCall);
MemoryStream stream = new MemoryStream(image);
docViewer.LoadDocument(stream);
edit As a potential workaround, I attempted to save the file into isolated storage with a ".pdf" extension. Then I use the IsolatedStorageFileStream to send to LoadDocument().
I've come to an actual error, it now says "PdfParserException was unhandled by user code: invalid file format (missing pdf header)"
Can anyone shed some light on this PDF header?
Here is an experiment I would conduct.
Add a button to your Xaml and on click use OpenFileDialog to get a FileInfo. From that FileInfo use its Open method to get a stream and pass that to docViewer.LoadDocument.
Now run it, click the button and select the same PDF document you are trying to send from the server.
If that succeeds you need to continue investigating your server streaming strategy. On the other hand if you still have the same problem, well it doesn't get more raw than that. Try other PDF files and start investigating the PDF component. Have you ever actually used it successfully, if so how does this current usage differ.
you should get the stream pointer back to 0 ,so this should do the trick
byte[] image = null;
image = Convert.FromBase64String(stringFromServerCall);
MemoryStream stream = new MemoryStream(image);
stream.Position = 0;
docViewer.LoadDocument(stream);

Parse csv or excel file in Silverlight

I've parsed these files in regular C# applications, but the IO methods for the files are different in Silverlight, and I can't seem to find the right methods. Searches haven't turned up any information I can use. For the real application I'll be receiving XML from the server, but for the prototype I just need to parse a file with some sample data in it.
You can save the Excel file as XML. An example can be found in this link
This way you can keep your import procedure the same and process the data as when you go live.
To access files from the user's machine you are required to use the OpenFileDialog and SaveFileDialog. Without elevated trust (requires out of browser apps) you will not be able to know anything more than the filename the user selected for input/saving; you will have no idea what the path is to this file. This function can only be called as the result of a user taking an action such as clicking a button; otherwise it will fail because Silverlight does not want malicious code prompting a user with annoying dialogs automatically.
To do this you would do something as follows:
var openFile = new OpenFileDialog();
if ( open.ShowDialog() == true ) // Sadly this is a nullable bool so this is necessary
{
using( Stream myStream = openFile.File.OpenRead() )
using ( var reader = new StreamReader( myStream ))
{
...
}
}

Resources