How to convert HTML content to PDF in Xamarin forms - c#

I want to convert HTML content to PDF. I have tried using third party API like GemBox, GrapeCity..
these all are working in UWP but in android failing.
Please suggest any solution. I can go with paid API's also.
Thanks!

If you are looking for a one-in-all solution, you can check out the leadtools document converter nuget here: https://www.nuget.org/packages/Leadtools.Document.Sdk/ disclaimer: i am employed by the vendor of this library
LEADTOOLS supports HTML -> PDF as well as a bunch of other formats. You can see more information here: https://www.leadtools.com/sdk/document/document-converter
This library supports Xamarin on Android, UWP, and iOS and is completely offline.
Here is a snippet of code that will work for your use-case:
using (var documentConverter = new DocumentConverter())
{
var htmlString = File.ReadAllText(#"./test.htm");
using (var ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(htmlString)))
{
var htmlDocument = DocumentFactory.LoadFromStream(ms, new LoadDocumentOptions());
var jobData = DocumentConverterJobs.CreateJobData(htmlDocument, "output.pdf", DocumentFormat.Pdf);
var job = documentConverter.Jobs.CreateJob(jobData);
documentConverter.Jobs.RunJob(job);
}
}

Related

Using C# iText 7 to flatten an XFA PDF

Is it possible to use iText 7 to flatten an XFA PDF? I'm only seeing Java documentation about it (http://developers.itextpdf.com/content/itext-7-examples/itext-7-form-examples/flatten-xfa-using-pdfxfa).
It seems like you can use iTextSharp, however to do this.
I believe it's not an AcroForm PDF because doing something similar to this answer How to flatten pdf with Itext in c#? simply created a PDF that wouldn't open properly.
It looks like you have to use iTextSharp and not iText7. Looking at the NuGet version it looks like iTextSharp is essentially the iText5 .NET version and like Bruno mentioned in the comments above, the XFA stuff simply hasn't been ported to iText7 for .NET.
The confusion stemmed from having both iText7 and iTextSharp versions in NuGet and also the trial page didn't state that the XFA worker wasn't available for the .NET version of iText7 (yet?)
I did the following to accomplish what I needed at least for a trial:
Request trial copy here: http://demo.itextsupport.com/newslicense/
You'll be emailed an xml license key, you can just place it on your desktop for now.
Create a new console application in Visual Studio
Open the Project Manager Console and type in the following and press ENTER (this will install other dependencies as well)
Install-Package itextsharp.xfaworker
Use the following code:
static void Main(string[] args)
{
ValidateLicense();
var sourcePdfPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "<your_xfa_pdf_file>");
var destinationPdfPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "output.pdf");
FlattenPDF(sourcePdfPath, destinationPdfPath);
}
private static void ValidateLicense()
{
var licenseFileLocation = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "itextkey.xml");
iTextSharp.license.LicenseKey.LoadLicenseFile(licenseFileLocation);
}
private static void FlattenPDF(string sourcePdfPath, string destinationPdfPath)
{
using (var sourcePdfStream = File.OpenRead(sourcePdfPath))
{
var document = new iTextSharp.text.Document();
var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new FileStream(destinationPdfPath, FileMode.Create));
var xfaf = new iTextSharp.tool.xml.xtra.xfa.XFAFlattener(document, writer);
sourcePdfStream.Position = 0;
xfaf.Flatten(new iTextSharp.text.pdf.PdfReader(sourcePdfStream));
document.Close();
}
}
The trial will put a huge watermark on the resulting PDF, but at least you can get it working and see how the full license should work.
For IText 7 this could be done in the following way
LicenseKey.LoadLicenseFile(#"Path of the license file");
MemoryStream dest_File = new MemoryStream();
XFAFlattener xfaFlattener = new XFAFlattener();
xfaFlattener.Flatten(new MemoryStream( File.ReadAllBytes(#"C:\\Unflattened file")), dest_File);
File.WriteAllBytes("flatten.pdf", dest_File.ToArray());

Handling intent callback Xamarin.forms

I basically want to be able to implement a feature for an android app to open a text file and read the contents to a string variable. I can handle this using android and Java but with forms I don't know how to go about it. I'm guessing dependency injection but a little guidance would do.
You can write your own file picker if required and use it via dependency service.
There is a plugin which does what you are asking for - FilePicker Plugin for Xamarin and Windows.
This can let you handle file handling from your pcl project.
The code is available in GitHub if you want to slightly customize it.
Eg :
private async Task PickFilesCommandHandler()
{
     var file = await CrossFilePicker.Current.PickFile();
     var fileEntity = new FileEntity
     {
         FileName = file.FileName,
         DataArray = file.DataArray
     };
}
Full example in Github.
For byte array to string conversion have a look at this answer.
Or use the following method via MemoryStream :
using (var ms = new MemoryStream(bytes))
{
using (var streamReader = new StreamReader(ms))
{
var str = streamReader.ReadToEnd();
}
}

C# OpenXML documentation understand animations in PowerPoint

I try to get animations from PowerPoint presentations, using DocumentFormat.OpenXml.dll. Which I tried is:
using (PresentationDocument presentationDocument = PresentationDocument.Open(pptPath, true))
{
var slidepart = presentationDocument.PresentationPart.SlideParts.First();
var slide = slidepart.Slide;
var xml = slide.OuterXml;
}
to get the first slide's XML. But I can't understand the entire XML structure and specific the animations tags.
Is there any good documentations about that, or some samples?
EDIT: I found next documentations and I started to read them:
Open XML SDK in GitHub
officeopenxml.com
Thank you!

Image file to PDF Conversion in Windows Phone Silverlight 8.1

I am writing Windows Phone 8.1 Silverlight app,
I have to convert Image File to PDF.
Is there any way, how to do it and which Libraries are available freely?
Thanks!!
There's a client site js library called jsPDF which is worth giving a try.
Here is the answer, whoever wants it. Its working and tested.
I have added ComponentOne Library in Windows Phone 8.1 Project.
using C1.Phone.Pdf;
using C1.Phone.PdfViewer;
C1PdfDocument pdf = new C1PdfDocument(PaperKind.PrcEnvelopeNumber3Rotated);
pdf.Landscape = true;
var rc = new System.Windows.Rect(20,30,300,200);
pdf.DrawImage(wbitmp, rc);
var fillingName = "Test.pdf";
var gettingFile = IsolatedStorageFile.GetUserStoreForApplication();
using (var loadingFinalStream = gettingFile.CreateFile(fillingName))
{
pdf.Save(loadingFinalStream);
}

Which library to use to extract text from images?

I am writing a program that when given an image of a low level math problem (e.g. 98*13) should be able to output the answer. The numbers would be black, and the background white. Not a captcha, just an image of a math problem.
The math problems would only have two numbers and one operator, and that operator would only be +, -, *, or /.
Obviously, I know how to do the calculating ;) I'm just not sure how to go about getting the text from the image.
A free library would be ideal... although If I have to write the code myself I could probably manage.
For extract words from image, I use the most accurate open source OCR engine: Tesseract. Available here or directly in your packages NuGet.
And this is my function in C#, which extract words from image passed in sourceFilePath. Set EngineMode to TesseractAndCube; it detect more word than the other options.
var path = "YourSolutionDirectoryPath";
using (var engine = new TesseractEngine(path + Path.DirectorySeparatorChar + "tessdata", "fra", EngineMode.TesseractAndCube))
{
using (var img = Pix.LoadFromFile(sourceFilePath))
{
using (var page = engine.Process(img))
{
var text = page.GetText();
// text variable contains a string with all words found
}
}
}
I hope that helps.
Try this post regarding using the C++ Google Tessaract OCR lib in C#
OCR with the Tesseract interface
You need OCR. There is the free Tesseract library from Google, but it's C code. You could use in a C++/CLI project and access via .NET.
This article gives some information on recognizing numbers (for Sudoku, but your problem is similar)
http://sudokugrab.blogspot.com/2009/07/how-does-it-all-work.html
you can use Microsoft Office Document Imaging (Interop.MODI.dll) in visaul studio and extract text of pictures
Document modiDocument = new Document();
modiDocument.Create(filePath);
modiDocument.OCR(MiLANGUAGES.miLANG_ENGLISH);
MODI.Image modiImage = (modiDocument.Images[0] as MODI.Image);
string extractedText = modiImage.Layout.Text;
modiDocument.Close();
return extractedText;
IronOCR is free for development and testing. The default English language pack should do a good job of reading this, but you may also want to consider using a custom Tesseract language pack written specifically for equations.
See https://ironsoftware.com/csharp/ocr/languages/#custom-language-example
using IronOcr;
var Ocr = new IronTesseract();
Ocr.UseCustomTesseractLanguageFile("languages/equ.traineddata");
using (var Input = new OcrInput(#"images\equation.png"))
{
var Result = Ocr.Read(Input);
Console.WriteLine(Result.Text);
}
Disclaimer: I work for Iron Software.

Categories

Resources