如何使用Base64图像与Itextsharp c#



在这个代码片段中,我使用它将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)
}

希望它能帮助

最新更新