У меня возникла проблема при печати PDF-файла с помощью библиотеки PDFsharp.
Я использую свойство Stream класса PdfPage для рисования страницы. Однако отображается ошибка нулевой ссылки, поскольку поток пуст.
Я не мог понять почему, поскольку PDF-файл существует и путь правильный.
Ниже приведен код:
public static void PrintPdfWithPrintDocument(string pdfPath)
{
if (!System.IO.File.Exists(pdfPath))
{
MessageBox.Show("Not Found.");
return;
}
pdfDoc = Pdf.IO.PdfReader.Open(pdfPath, Pdf.IO.PdfDocumentOpenMode.Modify);
CurrentPage = 0;
PrintDocument prnPdf = new PrintDocument();
prnPdf.PrintPage += OnPrintPage;
PrintDialog ptdPrinter = new PrintDialog();
ptdPrinter.AllowSomePages = true;
ptdPrinter.Document = prnPdf;
if (ptdPrinter.ShowDialog() == DialogResult.OK)
{
prnPdf.PrinterSettings = ptdPrinter.PrinterSettings;
prnPdf.Print();
}
}
private static void OnPrintPage(object sender, PrintPageEventArgs e)
{
if (CurrentPage < pdfDoc.PageCount)
{
pdfPage = pdfDoc.Pages(CurrentPage);
pdfGraphics = XGraphics.FromPdfPage(pdfPage, XGraphicsUnit.Millimeter);
pdfGraphics.MUH = Pdf.PdfFontEncoding.Unicode;
PdfSharp.Pdf.PdfDictionary.PdfStream pdfStream = (PdfSharp.Pdf.PdfDictionary.PdfStream)pdfPage.Stream;
MemoryStream imageStream = new MemoryStream(pdfStream.Value);
XRect xRect = new XRect(0, 0, e.PageBounds.Width, e.PageBounds.Height);
pdfGraphics.DrawImage(XImage.FromStream(imageStream), xRect);
CurrentPage += 1;
e.HasMorePages = CurrentPage < pdfDoc.PageCount;
}
else
e.HasMorePages = false;
}
Мне не хотелось использовать другую библиотеку или Acrobat Reader.
Я пытался найти другие способы сбора байтов со страницы. но я их не нашел.
Я установил библиотеки x86 и x64 из Pdfiumviewer
Решение:
public static void PrintPDF(string path)
{
try
{
PrintDialog printDialog = new PrintDialog();
printDialog.PrinterSettings = new PrinterSettings();
if (printDialog.ShowDialog() == DialogResult.OK)
{
PrinterSettings printerSettings = new PrinterSettings();
printerSettings.PrinterName = printDialog.PrinterSettings.PrinterName;
printerSettings.Copies = 1;
PageSettings pageSettings = new PageSettings(printerSettings);
pageSettings.Margins = new Margins(0, 0, 0, 0);
using (var document = PdfDocument.Load(path))
{
using (var printDocument = document.CreatePrintDocument())
{
printDocument.PrinterSettings = printerSettings;
printDocument.DefaultPageSettings = pageSettings;
printDocument.PrintController = new StandardPrintController();
printDocument.Print();
}
}
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred while printing the file: {ex.Message}");
}
}
Подробнее здесь: https://stackoverflow.com/questions/787 ... g-pdfsharp
Я не могу распечатать PDF-файл с помощью PDFsharp ⇐ C#
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Преобразование файлов DOCX в файлы PDF с помощью PDFsharp или MigraDoc в VB.NET.
Anonymous » » в форуме C# - 0 Ответы
- 22 Просмотры
-
Последнее сообщение Anonymous
-