我的代码很大,但我会让这很容易理解我想要实现的目标。我只是尝试使用 iText7 或 ItextSharp Core 库将 C# 中的 HTML 字符串转换为 PDF,然后它应该在 Android 中的临时或缓存目录中打开。
我在互联网上找到的这个例子对我有用:
MemoryStream stream = new MemoryStream();
PdfWriter writer = new PdfWriter(stream);
PdfDocument pdfDoc = new PdfDocument(writer);
Document document = new Document(pdfDoc);
// Add some text to the PDF
document.Add(new Paragraph("Hello, world!"));
// Close the document
document.Close();
// Create a copy of the MemoryStream
MemoryStream copyStream = new MemoryStream(stream.ToArray());
// Save the PDF to the Downloads folder
string fileName = "myPDF.pdf";
var downloadsPath = Path.Combine(FileSystem.CacheDirectory, "Downloads");
Directory.CreateDirectory(downloadsPath);
string filePath = Path.Combine(downloadsPath, fileName);
using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
{
await copyStream.CopyToAsync(fileStream);
}
// Launch the file using the FileLauncher
await Launcher.OpenAsync(new OpenFileRequest
{
File = new ReadOnlyFile(filePath)
});
但这不是我想要的,我想从 HTML 生成 PDF 格式的内容,所以到目前为止我已经尝试过了:
MemoryStream stream = new MemoryStream();
PdfWriter writer = new PdfWriter(stream);
PdfDocument pdfDoc = new PdfDocument(writer);
Document document = new Document(pdfDoc);
// Add some HTML content to the PDF
string html = "<html><body><h1>Hello, world!</h1></body></html>";
using (var htmlStream = new MemoryStream(Encoding.UTF8.GetBytes(html)))
{
HtmlConverter.ConvertToPdf(htmlStream, pdfDoc);
}
// Close the document
document.Close();
// Create a copy of the MemoryStream
MemoryStream copyStream = new MemoryStream(stream.ToArray());
// Save the PDF to the Downloads folder
string fileName = "myPDF.pdf";
var downloadsPath = Path.Combine(FileSystem.CacheDirectory, "Downloads");
Directory.CreateDirectory(downloadsPath);
string filePath = Path.Combine(downloadsPath, fileName);
using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
{
await copyStream.CopyToAsync(fileStream);
}
// Launch the file using the FileLauncher
await Launcher.OpenAsync(new OpenFileRequest
{
File = new ReadOnlyFile(filePath)
});
程序运行正常,但是当遇到以下行时:
HtmlConverter.ConvertToPdf(htmlStream, pdfDoc);
给了我这个错误:
System.UriFormatException:“无效的 URI:无法确定 URI 的格式。”
我该如何进行这项工作?也许我迷失在我的代码中,并且在从 html 字符串转换为 PDF 时可能是错误的。我把这个简单化了,因为我将从其他服务器获取一个大的 html 文件,并稍后将其设置为一个变量。
您可能想在示例中使用该库: