I am trying to create a simple example to embed an an image into a PDF either using HTML to PDF with image sharp or QuestPDF
with QuestPDF i have tried the following
public void Crear(string output)
{
try
{
var doc = Document.Create(container =>
container.Page(p => {
p.Size(PageSizes.A0.Landscape());
p.Content().Layers(l =>
{
l.PrimaryLayer().Stack(stack => {
var text = stack.Item().Text("Hello");
});
l.Layer().Image(( Model.CaraA_2 ));
});
//p.Content().Canvas((canva, e) =>
//{
// canva.DrawBitmap(GetBitmapFrom(Model.CaraA_2), new SKRect(600, 600, 500, 500));
//});
}
)
.Page(page => {
page.Size(PageSizes.A0.Landscape());
page.Content().Layers(l =>
{
l.PrimaryLayer().Stack(stack => {
var text =stack.Item().Text("Hello");
});
l.Layer().Image((Model.CaraB_1));
});
//page.Content().Canvas((canva, e) =>
//{
// canva.DrawBitmap(GetBitmapFrom(Model.CaraB_1), new SKRect(600, 600, 500, 500));
//});
})
);
doc.GeneratePdf(output);
}
catch (Exception ex)
{
}
}
this prints 2 empty pages in QuestPDF
while in ITextSharp it produces a PDF with the text but without the images... only is able to embed the qr core at the last part of the PDF here is the HTML text for the PDF https://gist.github.com/PontiacGTX/6c9ab85b0d33ccc550ada12f8ba43ab4 for Itextsharp
public static string CreatePdf(string[] body, string output)
{
float dpi = 100f;
float widthInches = (3600f *1.1f)/ dpi;
float heightInches =( 2575f*1.1f) / dpi;
var pageSize = new iTextSharp.text.Rectangle(widthInches * 72f, heightInches * 72f);
var rect = new iTextSharp.text.Rectangle(widthInches * 72f, heightInches * 72f);
iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(rect, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
using (MemoryStream memoryStream = new MemoryStream())
{
try
{
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
pdfDoc.Open();
for(var i=0;i< body.Length;i++)
{
htmlparser.Parse(new StringReader(body[i]));
if(body.Length>1 && body.Length-1!=i)
{
htmlparser.NewPage();
}
}
pdfDoc.Close();
byte[] bytes = memoryStream.ToArray();
System.IO.File.WriteAllBytes(output, bytes);
memoryStream.Close();
}
catch (Exception ex)
{
}
}
return output;
}
the code to convert the file to a base64:
private string ImagePathToBase64(string path,string mimeType)
{
if (!System.IO.File.Exists(path))
{
throw new Exception($"File not found {path}");
}
var bytes = System.IO.File.ReadAllBytes(path);
return $"data:{mimeType};base64,{Convert.ToBase64String(bytes)}";
}