Hi,
using below code (PDFSharp 3.5 beta 4) leads to different file sizes (after saving byte array resp stream to file) and different quality of graphics. But ... there's no difference in creation of pdf document.
Saving via bytearray or stream result in the same pdf quality, saving direct as file is slightly bigger and has a good quality. Attached zip contains 3 pdf's, please look at page 3 on each pdf - there you see my logo with described quality problems.
Code:
public partial class PdfBuilder
{
// default: 1 cm border on each side (except left side to have space for punch holes)
private XUnit _leftBorder = new XUnit(2, XGraphicsUnit.Centimeter);
private XUnit _topBorder = new XUnit(1, XGraphicsUnit.Centimeter);
private XUnit _rightBorder = new XUnit(1, XGraphicsUnit.Centimeter);
private XUnit _bottomBorder = new XUnit(1, XGraphicsUnit.Centimeter);
private void SetBorder(double left, double top, double right, double bottom, XGraphicsUnit xGraphicsUnit)
{
_leftBorder = new XUnit(left, xGraphicsUnit);
_topBorder = new XUnit(top, xGraphicsUnit);
_rightBorder = new XUnit(right, xGraphicsUnit);
_bottomBorder = new XUnit(bottom, xGraphicsUnit);
}
private void CreatePdfFromImages(IEnumerable<Image> images, string fileName)
{
var doc = new PdfDocument(fileName);
CreatePdf(images, doc);
doc.Close(); // this will save the document
}
private void CreatePdfFromImages(IEnumerable<Image> images, out byte[] pdfArray)
{
var h = new MemoryStream();
var doc = new PdfDocument(h);
CreatePdf(images, doc);
using (var ms = new MemoryStream())
{
doc.Save(ms, false);
pdfArray = ms.ToArray();
}
}
private void CreatePdfFromImages(IEnumerable<Image> images, out MemoryStream pdf)
{
pdf = new MemoryStream();
var h = new MemoryStream();
var doc = new PdfDocument(h);
CreatePdf(images, doc);
doc.Save(pdf, false);
doc.Close();
pdf.Seek(0, SeekOrigin.Begin);
}
private void CreatePdf(IEnumerable<Image> images, PdfDocument document)
{
document.Info.CreationDate = DateTime.Now;
document.Info.Author = "holonsoft.pdf";
foreach (var rawImage in images)
{
var page = document.AddPage();
page.Size = PageSize.A4;
page.TrimMargins.Left = _leftBorder;
page.TrimMargins.Right = _rightBorder;
page.TrimMargins.Top = _topBorder;
page.TrimMargins.Bottom = _bottomBorder;
var graphics = XGraphics.FromPdfPage(page);
using (var imgStream = ConvertImageToStream(rawImage))
{
var image = XImage.FromStream(imgStream);
graphics.DrawImage(image, 0, 0);
}
}
}
private Stream ConvertImageToStream(Image rawImage)
{
var result = new MemoryStream();
rawImage.Save(result, rawImage.RawFormat);
return result;
}
}
Code:
_pdfBuilder.CreatePdfFromImages(imgList, out pdfStream);
var f = new FileStream(_fileNameViaStream, FileMode.CreateNew);
pdfStream.CopyTo(f);
f.Close();
Code:
byte[] array;
_pdfBuilder.CreatePdfFromImages(imgList, out array);
File.WriteAllBytes(_fileNameViaArray, array);