在此代码片段中,我用它来将 HTML 转换为 PDF,然后再转换回
MemoryStream
。
private MemoryStream createPDF(string html)
{
try
{
MemoryStream msOutput = new MemoryStream();
TextReader reader = new StringReader(html);
Document document = new Document(PageSize.A4, 30, 30, 30, 30);
PdfWriter writer = PdfWriter.GetInstance(document, msOutput);
HTMLWorker worker = new HTMLWorker(document);
document.Open();
worker.StartDocument();
worker.Parse(reader); //error occurs in here
worker.EndDocument();
worker.Close();
document.Close();
var bytedata = msOutput.ToArray();
var pdfContent = new MemoryStream(bytedata);
return pdfContent;
}
catch (Exception ex)
{
throw;
}
}
但是当 HTML 内容包含 Base64 图像时。我在这一行中收到此错误 (
worker.Parse(reader);
)。
The URI prefix is not recognized.
我做了几个解决方法,并且知道发生这种情况是因为可以解释
itextsharp
的 URI 必须没有数据前缀。我该如何解决这个问题?
您好,我已经在 base64 中实现了图像的小型管理(对我来说来自 html 上传,所以我也删除了标签)。我报告解决方案,同时知道您将会解决(考虑到过去的时间),但至少如果其他人有相同的问题,他们将有一个起始输入
VB代码
Dim myText As String = dictionary.Item("@template.testo").ToString()
Dim phrase As String = "<img src=""data:image/png;base64,"
Dim phrase2 As String = """ alt="""">"
Dim Occurrences As Integer = (myText.Length - myText.Replace(phrase, String.Empty).Length) / phrase.Length
For value As Integer = 0 To Occurrences
Dim immagineBase64 As String = myText.Substring(myText.IndexOf(phrase), myText.IndexOf(phrase2) - (phrase2.Length + 2)).Replace(phrase, "").Replace(phrase2, "")
Dim imageBytes As Byte() = Convert.FromBase64String(immagineBase64)
Dim image As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(imageBytes)
documento.Add(image)
myText = myText.Replace(myText.Substring(myText.IndexOf(phrase), myText.IndexOf(phrase2) - (phrase2.Length + 2)), "")
Next
C# 代码
string myText = dictionary.Item("@template.testo").ToString() // my base64 image with html tag
string phrase = "<img src=\"data:image/png;base64,"
string phrase2 = "\" alt=\"\">"
int Occurrences = (myText.Length - myText.Replace(phrase, String.Empty).Length) / phrase.Length
for(int value = 0; value < Occurrences; value++){
string immagineBase64 = myText.Substring(myText.IndexOf(phrase), myText.IndexOf(phrase2) - (phrase2.Length + 2)).Replace(phrase, "").Replace(phrase2, "")
Byte[] imageBytes = Convert.FromBase64String(immagineBase64)
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imageBytes)
documento.Add(image)
}
希望有帮助
您只需以 64 为基数创建字节数组和图像。
Document doc = new Document(PageSize.LETTER, 25, 25, 110, 25);
string imgBase64 = "iVBORw0KGgoAAAANSUhEUgAAClgAAAE0CAYAAABKe6wlA...";
Byte[] bytes = Convert.FromBase64String(imgBase64 );
Image image = Image.GetInstance(bytes);
doc.Add(image);