Open Kingdom-Of-Heaven opened 3 years ago
Try this:
/// <summary>
/// Converts HTML text to PNG
/// </summary>
/// <param name="html">HTML string to be converted to PDF</param>
/// <param name="fileName">Name (not path), excluding suffix, of PDF file</param>
/// <param name="pageSize">PDF page size, in points. (default based upon user's region)</param>
/// <param name="margin">PDF page's margin, in points. (default is zero)</param>
/// <returns></returns>
public static async Task<ToFileResult2> ToPdfAsync(this string html, string fileName, PageSize pageSize = default, PageMargin2 margin = default)
{
_platformToPdfService = _platformToPdfService ?? DependencyService.Get<IToPdfService2>();
if (_platformToPdfService == null)
throw new NotSupportedException("Cannot get HtmlService: must not be supported on this platform.");
ToFileResult2 result = null;
using (var indicator = ActivityIndicatorPopup.Create())
{
if (pageSize is null || pageSize.Width <= 0 || pageSize.Height <= 0)
pageSize = PageSize.Default;
margin = margin ?? new PageMargin2();
if (pageSize.Width - margin.HorizontalThickness < 1 || pageSize.Height - margin.VerticalThickness < 1)
return new ToFileResult2(true, "Page printable area (page size - margins) has zero width or height.");
result = await _platformToPdfService.ToPdfAsync(html, fileName, pageSize, margin);
}
await Task.Delay(50);
return result;
}
Thanks, @smalgin for helping!
Thanks to you! AFAIR You can also set custom Margin in the latest version.
NOTE: proper pagination (eq footers, headers) is ANOTHER issue & requires significant time investment. It is on my TODO list, but with a low priority... either I will fix it in 2022 or by that time I'll have budget to pay somebody to do this for me :)
but why additionaly converting html to pdf?
I use html as source format because I need some formatting and logo. Simple text only has paragraphs and indentation. Pick based on requirements
Hmm not working for me i did:
public async Task printme()
{
if (Forms9Patch.PrintService.CanPrint)
{
var myHtmlString = @"
<!DOCTYPE html>
<html>
<body>
<h1>Something</h1>
</body>
</html>
";
var aaa = await myHtmlString.ToPdfAsync("MojaNazwaPliku", PageSize.IsoA5);
await aaa.Result.PrintAsync("my_print_job_name");
}
}
After that on pdf in printer preview i see text like: MojaNazwaPliku9827398798237489234.pdf
innstead of my myHtmlString'
WHat am i doing wrong?
I honestly don't know. I never did any printing - I just save PDF files. I suspect your result is a file name, that's why you see filename printed.
Yes i see that this line:
await aaa.Result.PrintAsync("my_print_job_name");
gives me the created pdf's path.
Do you know how can i stream that pdf i mean how to convert it to string based on given path?
It works nice when i just use this code below. Nevertheless how can i set paper format like A4 or A5 ?