Xamarin免费HTML或DOC到PDF转换

时间:2016-05-20 07:41:50

标签: html pdf xamarin docx doc

我目前正在搜索图书馆或在手机/标签上将HTML或DOCX文件转换为PDF格式的方式,主要是我正在寻找Android或iOS idk的方式,如果它是PCL或平台特定方法。我可以独立地为每个平台执行此操作,因为我们的应用程序需要iOS 8或android kitkat,两者都支持原生PDF转换,但我想为用户无缝地完成,所以问题是,如果有人之前已经这样做,而不加载它首先进入一个可见的Webview,或者知道一个开放的非GPL许可API(不能发布代码),用Xamarin来做这个。

我知道可以在线进行此操作,但我不想依赖于在线服务。

感谢帮助和想法。

3 个答案:

答案 0 :(得分:3)

Android解决方案:

通过依赖服务(如

)调用SafeHTMLToPDF(字符串html,字符串文件名)
DependencyService.Get<YOURINTERFACE>().SafeHTMLToPDF(htmlString, "Invoice");


   public string SafeHTMLToPDF(string html, string filename)
    {

        var dir = new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/pay&go/");
        var file = new Java.IO.File(dir + "/" + filename + ".pdf");

        if (!dir.Exists())
            dir.Mkdirs();


        int x = 0;
        while (file.Exists())
        {
            x++;
            file= new Java.IO.File(dir + "/" + filename + "( " + x + " )" + ".pdf");
        }

        if (webpage == null)
            webpage = new Android.Webkit.WebView(GetApplicationContext());

        int width = 2102;
        int height = 2973;

        webpage.Layout(0, 0, width, height);
        webpage.LoadDataWithBaseURL("",html, "text/html", "UTF-8" , null);
        webpage.SetWebViewClient(new WebViewCallBack(file.ToString()));

        return file.ToString();
    }


    class WebViewCallBack : WebViewClient
    {

        string fileNameWithPath = null;

        public WebViewCallBack(string path)
        {
            this.fileNameWithPath = path;
        }


        public override void OnPageFinished(Android.Webkit.WebView myWebview, string url)
        {
            PdfDocument document = new PdfDocument();
            PdfDocument.Page page = document.StartPage(new PdfDocument.PageInfo.Builder(2120 ,3000, 1).Create());

            myWebview.Draw(page.Canvas);
            document.FinishPage(page);
            Stream filestream = new MemoryStream();
            FileOutputStream fos = new Java.IO.FileOutputStream(fileNameWithPath, false); ;
            try
            {
                document.WriteTo(filestream);
                fos.Write(((MemoryStream)filestream).ToArray(), 0, (int)filestream.Length);
                fos.Close();
            }
            catch
            {
            }
        }
    }

在iOS下完成它的方法

public string SafeHTMLToPDF(string html, string filename)
    {
        UIWebView webView = new UIWebView(new CGRect(0, 0, 6.5 * 72, 9 * 72));


        var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        var file = Path.Combine(documents, "Invoice" + "_" + DateTime.Now.ToShortDateString() + "_" + DateTime.Now.ToShortTimeString() + ".pdf");

        webView.Delegate = new WebViewCallBack(file);
        webView.ScalesPageToFit = true;
        webView.UserInteractionEnabled = false;
        webView.BackgroundColor = UIColor.White;
        webView.LoadHtmlString(html, null);



        return file;
    }

    class WebViewCallBack : UIWebViewDelegate
    {

        string filename = null;
        public WebViewCallBack(string path)
        {
            this.filename = path;

        }
        public override void LoadingFinished(UIWebView webView)
        {
            double height, width;
            int header, sidespace;

            width = 595.2;
            height = 841.8;
            header = 10;
            sidespace = 10;


            UIEdgeInsets pageMargins = new UIEdgeInsets(header, sidespace, header, sidespace);
            webView.ViewPrintFormatter.ContentInsets = pageMargins;

            UIPrintPageRenderer renderer = new UIPrintPageRenderer();
            renderer.AddPrintFormatter(webView.ViewPrintFormatter, 0);

            CGSize pageSize = new CGSize(width, height);
            CGRect printableRect = new CGRect(sidespace,
                              header,
                              pageSize.Width - (sidespace * 2),
                              pageSize.Height - (header * 2));
            CGRect paperRect = new CGRect(0, 0, width, height);
            renderer.SetValueForKey(NSValue.FromObject(paperRect), (NSString)"paperRect");
            renderer.SetValueForKey(NSValue.FromObject(printableRect), (NSString)"printableRect");
            NSData file = PrintToPDFWithRenderer(renderer, paperRect);
            File.WriteAllBytes(filename, file.ToArray());
        }

        private NSData PrintToPDFWithRenderer(UIPrintPageRenderer renderer, CGRect paperRect)
        {
            NSMutableData pdfData = new NSMutableData();
            UIGraphics.BeginPDFContext(pdfData, paperRect, null);

            renderer.PrepareForDrawingPages(new NSRange(0, renderer.NumberOfPages));

            CGRect bounds = UIGraphics.PDFContextBounds;

            for (int i = 0; i < renderer.NumberOfPages; i++)
            {
                UIGraphics.BeginPDFPage();
                renderer.DrawPage(i, paperRect);
            }
            UIGraphics.EndPDFContent();

            return pdfData;
        }

    }

答案 1 :(得分:0)

对现有解决方案感到沮丧,我建立了一些扩展方法(OpenSource,获得MIT许可),将HTML或Xamarin.Forms.WebView的内容转换为PDF文件。 WebView到PDF的用法示例:

        async void ShareButton_Clicked(object sender, EventArgs e)
        {
            if (Forms9Patch.ToPdfService.IsAvailable)
            {
                if (await webView.ToPdfAsync("output.pdf") is ToFileResult pdfResult)
                {
                    if (pdfResult.IsError)
                        using (Toast.Create("PDF Failure", pdfResult.Result)) { }
                    else
                    {
                        var collection = new Forms9Patch.MimeItemCollection();
                        collection.AddBytesFromFile("application/pdf", pdfResult.Result);
                        Forms9Patch.Sharing.Share(collection, shareButton);
                    }
                }
            }
            else
                using (Toast.Create(null, "PDF Export is not available on this device")) { }
        }
    }

有关如何使用它的更完整说明,这是一篇简短的文章:https://medium.com/@ben_12456/share-xamarin-forms-webview-as-a-pdf-a877542e824a

答案 2 :(得分:-1)

是的,您可以轻松地使用几行代码将Xamarin中的Word文档转换为PDF。您需要参考nuget.org

中的Syncfusion.Xamarin.DocIORenderer
Assembly assembly = typeof(App).GetTypeInfo().Assembly;
// Retrieves the document stream from embedded Word document
Stream inputStream = assembly.GetManifestResourceStream("WordToPDF.Assets.GettingStarted.docx");
string fileName = "GettingStarted.pdf";
// Creates new instance of WordDocument
WordDocument wordDocument = new WordDocument(inputStream,Syncfusion.DocIO.FormatType.Automatic);
inputStream.Dispose();
// Creates new instance of DocIORenderer for Word to PDF conversion
DocIORenderer render = new DocIORenderer();
// Converts Word document into PDF document
PdfDocument pdfDocument = render.ConvertToPDF(wordDocument);
// Releases all resources used by the DocIORenderer and WordDocument instance
render.Dispose();
document.Close();
// Saves the converted PDF file
MemoryStream outputStream = new MemoryStream();
pdfDocument.Save(outputStream);
// Releases all resources used by the PdfDocument instance
pdfDocument.Close();

要了解更多相关信息,请参阅here