Create PDF file with images in WinRT - pdf

How I can create PDF files from a list of image in WinRT. I found something similar for windows phone 8 here("Converting list of images to pdf in windows phone 8") But I am looking for a solution for windows 8. If anyone of having knowledge about this please share your thoughts with me.

Try http://jspdf.com/
This should work on WinJS, but I haven't tested it. In a XAML app you can try to host a web browser control with a jsPDF-enabled page.

ComponentOne has now released the same PDF library that they had in Windows Phone for Windows Runtime. Tho it's not open source, of course.

Amyuni PDF Creator for WinRT (a commercial library) could be used for this task. You can create a new PDF file by creating a new instance of the class AmyuniPDFCreator.IacDocument, then add new pages with the method AddPage, and add pictures to each page by using the method IacPage.CreateObject.
The code in C# for adding a picture to a page will look like this:
public IacDocument CreatePDFFromImage()
{
IacDocument pdfDoc = new IacDocument();
// Set the license key
pdfDoc.SetLicenseKey("Amyuni Tech.", "07EFCD0...C4FB9CFD");
IacPage targetPage = pdfDoc.GetPage(1); // A new document will always be created with an empty page
// Adding a picture to the current page
using (Stream imgStrm = await Windows.ApplicationModel.Package.Current.InstalledLocation.OpenStreamForReadAsync("pdfcreatorwinrt.png"))
{
IacObject oPic = page.CreateObject(IacObjectType.acObjectTypePicture, "MyPngPicture");
BinaryReader binReader = new BinaryReader(imgStrm);
byte[] imgData = binReader.ReadBytes((int)imgStrm.Length);
// The "ImageFileData" attribute has not been added yet to the online documentation
oPic.AttributeByName("ImageFileData").Value = imgData;
oPic.Coordinates = new Rect(100, 2000, 1200, 2000);
}
return pdfDoc;
}
Disclaimer: I currently work as a developer of the library
For an "open source" alternative it might be better for you to rely on a web service that creates the PDF file using one of the many open source libraries available.

I think this may help you if you want to convert an image (.jpg) file to a PDF file.
Its working in my lab.
string source = "image.jpg";
string destinaton = "image.pdf";
PdfDocument doc = new PdfDocument();
doc.Pages.Add(new PdfPage());
XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[0]);
XImage img = XImage.FromFile(source);
xgr.DrawImage(img, 0, 0);
doc.Save(destinaton);
doc.Close();
Thanks.

Related

Generating and Downloading a PDF

I am developing an Android app for flight reservation and i am using firebase Database for storing and retriving data. I need to generate a PDF of Ticket and contents should be changed as per passenger details and stored in local directory. I have a template of Ticket. What should i do?
Thank you in advance.
Since Android 5 you can use PdfDocument and its friend classes to generate a PDF document on Android device. The official documentation is here. There is no library to use a template with PdfDocument. You have to use some drawing primitive to accomplish your task.
Here is a sample to generate a PDF with a single page A4:
// create a new document
PdfDocument document = new PdfDocument();
// crate a page description
PageInfo pageInfo = new PageInfo.Builder(595, 842, 1).create();
// start a page
Page page = document.startPage(pageInfo);
Canvas canvas=page.getCanvas());
// draw something on the page
Paint paint = new Paint();
paint.setColor(Color.RED);
canvas.drawCircle(50, 50, 30, paint);
// finish the page
document.finishPage(page);
// write the document content
document.writeTo(getOutputStream());
// close the document
document.close();
The page content is defined with Canvas object. Just another example. I hope this helps you.

Print PDF in Website

I have been searching for days for a solution to this problem.
Description : I have a website which loads a PDF dynamically via an iFrame. The PDF is saved on the server and the user of the website can view the pdf on the website.
Problem : Introduce a Print button on website which prints the PDF which was created dynamically and saved on the server.
Is this even possible ? I am looking at a cross-browser implementation as well to make things worse. I have tried n number of JS options from the web but none of them seem to work. I can not seem to get the PDF printed in the same way as it looks. To put it short, I am trying to emulate the print button which appears on the PDF when it is loaded. Is there an option to pass the pdf document from the server to the print dialog box ?
Description : I have a website which loads a PDF dynamically via an iFrame. The PDF is saved on the server and the user of the website can view the pdf on the website.
Problem : Introduce a Print button on website which prints the PDF which was created dynamically and saved on the server.
Solution : I could not find an exact solution to this problem, but here is how I solved the problem -
Create the 'Print' as per req and redirect that to another page which has only the PDF.
Copy the previous PDF & Create new PDF with JS - this.print() such that when it opens up, the print dialog pops up directly to the user.
In the new page -
if ("Location of PDF " != null)
{
sPdf = "Location of PDF ";
PdfReader pReader = new PdfReader(sPdf);
Document document = new Document
(pReader.GetPageSizeWithRotation(ApplicationConstants.INDEX_ONE));
int n = pReader.NumberOfPages;
FileStream fs = new FileStream
("New PDF location",
FileMode.Create, FileAccess.Write);
PdfCopy copy = new PdfCopy(document, fs);
// Write to pdf
document.Open();
for (int i = ApplicationConstants.INDEX_ONE; i <= n; i++)
{
PdfImportedPage page = copy.GetImportedPage(pReader, i);
copy.AddPage(page);
}
copy.AddJavaScript("this.print(true);", true);
document.Close();
pReader.Close();
inStr = File.OpenRead("New PDF location");
while ((bytecnt = inStr.Read
(buffer, ApplicationConstants.INDEX_ZERO, buffer.Length))
> ApplicationConstants.INDEX_ZERO)
{
if (Context.Response.IsClientConnected)
{
Context.Response.ContentType = "application/PDF";
Context.Response.OutputStream.Write(buffer,
ApplicationConstants.INDEX_ZERO, buffer.Length);
Context.Response.Flush();
}
}
}
Please note that I am using itextsharp to inject the JS script into the new PDF. Hope this helps someone else. I am trying to find another solution without the usage of itextsharp or any other dll but this will have to do for now.
I am not sure if this will work, but you could try launching a popup window with a special version of your PDF file that opens the print dialog when opened. Then close the popup afterwards. This last part might be tricky since I think there is no clean way to know if the print dialog has been closed.

Print one page of WebBrowser

I am trying to automate printing of intranet websites. Since this is an application that will be put on a specific user's computer, which will be run on an as-needed basis, I'd like it to be as un-disruptive as possible (in other words, not launching IE for each page). The catch is that I need to print the first page of the website and then print the whole website again, which will produce the first page two times. What is the best way to do this?
I have no problem getting it to loop through the pages that it needs to print, nor do I have a problem opening the page with webbrowser. I do, however, have a problem specifying a print range.
I also tried PrintDocument, but couldn't figure out how to get that to open within the form.
Thanks for any help that can be provided.
To download the pdf file, try this solution using iTextSharp:
ITextSharp HTML to PDF?
Except with one substitution if you want to save directly to a file
private MemoryStream createPDF(string html)
{
MemoryStream msOutput = new MemoryStream();
TextReader reader = new StringReader(html);
// step 1: creation of a document-object
Document document = new Document(PageSize.A4, 30, 30, 30, 30);
// step 2:
// we create a writer that listens to the document
// and directs a XML-stream to a file
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("c:\\my.pdf", FileMode.Create));
// step 3: we create a worker parse the document
HTMLWorker worker = new HTMLWorker(document);
// step 4: we open document and start the worker on the document
document.Open();
worker.StartDocument();
// step 5: parse the html into the document
worker.Parse(reader);
// step 6: close the document and the worker
worker.EndDocument();
worker.Close();
document.Close();
return msOutput;
}
Once the PDF is set up, try ghostscript to print one page:
Print existing PDF (or other files) in C#
If you start a shell execute of the process, you can use the command line arguments:
gsprint "filename.pdf" -from 1 - to 1
Alternatively, WebBrowser can just print the full page: http://msdn.microsoft.com/en-us/library/b0wes9a3.aspx
I can't find anything referencing that WebBrowser itself can print "From page X to Y" without a print dialog.
Since I'm facing a similar problem, here's an alternate solution:
This open source project turns HTML documents to PDF documents similar to iTextSharp (http://code.google.com/p/wkhtmltopdf/). We ended up not using iTextSharp because of several formatting issues with the way the site we wanted to print was laid out. We send command line arguments to turn the html downloaded using a webclient into a pdf file.
WebClient wc = new WebClient();
wc.Credentials = CredentialCache.DefaultNetworkCredentials;
string htmlText = wc.DownloadString("http://websitehere.com);
Then, after turning to pdf, you can simply print the file:
Process p = new Process();
p.StartInfo.FileName = string.Format("{0}.pdf", fileLocation);
p.StartInfo.Verb = "Print";
p.Start();
p.WaitForExit();
(Apologies for C#, I'm more familiar with it than VB.NET, though it should be a simple conversion)

How to get an image from mshtml.htmlimg to hard disk

Without using API?
I know there are several way.
I am using mshtml library by the way, which is better than webbrowser control. I am effectively automating internet explorer straight.
Basically I prefer a way to take the image straight without having to know the URL of the htmlimg and download it.
I know I can take URL from the image element and downloading it with webclient. The image changes depending on cookies and IP. So that wouldn't do.
I want the exact images displayed by the htmlimg element to be the one stored.
Basically as if someone is taking a local screenshot of what shows up on screen.
There's an old solution for this here:
http://p2p.wrox.com/c/42780-mshtml-how-get-images.html#post169674
These days though you probably want to check out the Html Agility Pack:
http://htmlagilitypack.codeplex.com/
The documentation isn't exactly great however; so this code snippet may help:
HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(html);
// You can also load a web page by utilising WebClient and loading in the stream - use one of the htmlDoc.Load() overloads
var body = htmlDoc.DocumentNode.Descendants("body").FirstOrDefault();
foreach (var img in body.Descendants("img"))
{
var fileUrl = img.Attributes["src"].Value;
var localFile = #"c:\localpath\tofile.jpg";
// Download the image using WebClient:
using (WebClient client = new WebClient())
{
client.DownloadFile("fileUrl", localFile);
}
}

Displaying Tiff files in SSRS reports

I have a requirement to be be able to embed scanned tiff images into some SSRS reports.
When I design a report in VS2005 and add an image control the tiff image displays perfectly however when I build it. I get the warning :
Warning 2 [rsInvalidMIMEType] The value of the MIMEType property for the image ‘image1’ is “image/tiff”, which is not a valid MIMEType. c:\SSRSStuff\TestReport.rdl 0 0
and instead of an image I get the little red x.
Has anybody overcome this issue?
Assuming you're delivering the image file via IIS, use an ASP.NET page to change image formats and mime type to something that you can use.
Response.ContentType = "image/png";
Response.Clear();
using (Bitmap bmp = new Bitmap(tifFilepath))
bmp.Save(Response.OutputStream, ImageFormat.Png);
Response.End();
I have been goggling fora solution on how to display a TIFF image in a SSRS report but I couldn't find any and since SSRS doesn's support TIFF, I thought converting the TIFF to one of the suppported format will do the trick. And it did. I don't know if there are similar implementation like this out there, but I am just posting so others could benefit as well.
Note this only applies if you have a TIFF image saved on database.
Public Shared Function ToImage(ByVal imageBytes As Byte()) As Byte()
Dim ms As System.IO.MemoryStream = New System.IO.MemoryStream(imageBytes)
Dim os As System.IO.MemoryStream = New System.IO.MemoryStream()
Dim img As System.Drawing.Image = System.Drawing.Image.FromStream(ms)
img.Save(os, System.Drawing.Imaging.ImageFormat.Jpeg)
Return os.ToArray()
End Function
Here’s how you can use the code:
1. In the Report Properties, Select Refereneces, click add and browse System.Drawing, Version=2.0.0.0
2. Select the Code Property, Copy paste the function above
3. Click Ok
4. Drop an Image control from the toolbox
4.1. Right-Click the image and select Image Properties
4.2. Set the Image Source to Database
4.3. In the Use this field, Click expression and paste the code below
=Code.ToImage(Fields!FormImage.Value)
4.4. Set the appropriate Mime to Jpeg
Regards,
Fulbert
Thanks Peter your code didn't compile but the idea was sound.
Here is my attempt that works for me.
protected void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "image/jpeg";
Response.Clear();
Bitmap bmp = new Bitmap(tifFileLocation);
bmp.Save(Response.OutputStream, ImageFormat.Jpeg);
Response.End();
}