Как распечатать PDF-документы на C# и .NET с помощью Adobe, Foxit.


Если вы хотите распечатать PDF-документ на принтере и бумаге, вам просто нужно использовать наш пример кода, который позволяет печатать PDF-файлы с помощью Abobe Reader, Foxit Reader.

Прежде всего, давайте создадим простой документ с надписью: " Здравствуйте, Дорогие друзья" и сохраните документ в формате PDF:

             // Let's create a simple PDF document.
            DocumentCore dc = new DocumentCore();

            // Add new section.
            Section section = new Section(dc);
            dc.Sections.Add(section);

            // Let's set page size A4.
            section.PageSetup.PaperType = PaperType.A4;

            // Add a paragraph using ContentRange:
            dc.Content.End.Insert("\nHi Dear Friends.", new CharacterFormat() { Size = 25, FontColor = Color.Blue, Bold = true });
            SpecialCharacter lBr = new SpecialCharacter(dc, SpecialCharacterType.LineBreak);
            dc.Content.End.Insert(lBr.Content);
            dc.Content.End.Insert("I'm happy to see you!", new CharacterFormat() { Size = 20, FontColor = Color.DarkGreen, UnderlineStyle = UnderlineType.Single });

            // Save PDF to a file
            dc.Save(pdfPath, new PdfSaveOptions());

Следующий шаг: Создайте новый процесс: Acrobat Reader. Вы можете изменить его в Foxit Reader.

                      string processFilename = Microsoft.Win32.Registry.LocalMachine
                     .OpenSubKey("Software")
                     .OpenSubKey("Microsoft")
                     .OpenSubKey("Windows")
                     .OpenSubKey("CurrentVersion")
                     .OpenSubKey("App Paths")
                     .OpenSubKey("AcroRd32.exe")
                     .GetValue(String.Empty).ToString();


И последний шаг - это печать PDF-файла.

            // Let's transfer our PDF file to the process Adobe Reader
            ProcessStartInfo info = new ProcessStartInfo();
            info.Verb = "print";
            info.FileName = processFilename;
            info.Arguments = String.Format("/p /h {0}", pdfPath);
            info.CreateNoWindow = true;
            
            //(It won't be hidden anyway... thanks Adobe!)
            info.WindowStyle = ProcessWindowStyle.Hidden;
            info.UseShellExecute = false;

            Process p = Process.Start(info);
            p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

 

Отличная работа!

Полный код

using SautinSoft.Document;
using System;
using System.IO;
using System.Text;
using System.Diagnostics;

namespace Example
{
    class Program
    {       
        static void Main(string[] args)
        {
            CreateAndPrintPdf();
        }

        /// <summary>
        /// Creates a new document and saves it into PDF format. Print PDF using your default printer.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/print-document-net-csharp-vb.php
        /// </remarks>
        public static void CreateAndPrintPdf()
        {
            // Set the path to create pdf document.
            string pdfPath = @"Result.pdf";

            // Let's create a simple PDF document.
            DocumentCore dc = new DocumentCore();

            // Add new section.
            Section section = new Section(dc);
            dc.Sections.Add(section);

            // Let's set page size A4.
            section.PageSetup.PaperType = PaperType.A4;

            // Add a paragraph using ContentRange:
            dc.Content.End.Insert("\nHi Dear Friends.", new CharacterFormat() { Size = 25, FontColor = Color.Blue, Bold = true });
            SpecialCharacter lBr = new SpecialCharacter(dc, SpecialCharacterType.LineBreak);
            dc.Content.End.Insert(lBr.Content);
            dc.Content.End.Insert("I'm happy to see you!", new CharacterFormat() { Size = 20, FontColor = Color.DarkGreen, UnderlineStyle = UnderlineType.Single });

            // Save PDF to a file
            dc.Save(pdfPath, new PdfSaveOptions());

            // Create a new process: Acrobat Reader. You may change in on Foxit Reader.
            string processFilename = Microsoft.Win32.Registry.LocalMachine
                     .OpenSubKey("Software")
                     .OpenSubKey("Microsoft")
                     .OpenSubKey("Windows")
                     .OpenSubKey("CurrentVersion")
                     .OpenSubKey("App Paths")
                     .OpenSubKey("Acrobat.exe")
                     .GetValue(String.Empty).ToString();

            // Let's transfer our PDF file to the process Adobe Reader
            ProcessStartInfo info = new ProcessStartInfo();
            info.Verb = "print";
            info.FileName = processFilename;
            info.Arguments = String.Format("/p /h {0}", pdfPath);
            info.CreateNoWindow = true;
            
            //(It won't be hidden anyway... thanks Adobe!)
            info.WindowStyle = ProcessWindowStyle.Hidden;
            info.UseShellExecute = false;

            Process p = Process.Start(info);
            p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

            // Print our PDF
            int counter = 0;
            while (!p.HasExited)
            {
                System.Threading.Thread.Sleep(1000);
                counter += 1;
                if (counter == 5) break;
            }
            if (!p.HasExited)
            {
                p.CloseMainWindow();
                p.Kill();
            }

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(pdfPath) { UseShellExecute = true });
        }
    }
}

Download

Imports Microsoft.VisualBasic
Imports SautinSoft.Document
Imports System
Imports System.IO
Imports System.Text
Imports System.Diagnostics

Namespace Example
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			CreateAndPrintPdf()
		End Sub

		''' <summary>
		''' Creates a new document and saves it into PDF format. Print PDF using your default printer.
		''' </summary>
		''' <remarks>
		''' Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/print-document-net-csharp-vb.php
		''' </remarks>
		Public Shared Sub CreateAndPrintPdf()
			' Set the path to create pdf document.
			Dim pdfPath As String = "Result.pdf"

			' Let's create a simple PDF document.
			Dim dc As New DocumentCore()

			' Add new section.
			Dim section As New Section(dc)
			dc.Sections.Add(section)

			' Let's set page size A4.
			section.PageSetup.PaperType = PaperType.A4

			' Add a paragraph using ContentRange:
			dc.Content.End.Insert(vbLf & "Hi Dear Friends.", New CharacterFormat() With {
				.Size = 25,
				.FontColor = Color.Blue,
				.Bold = True
			})
			Dim lBr As New SpecialCharacter(dc, SpecialCharacterType.LineBreak)
			dc.Content.End.Insert(lBr.Content)
			dc.Content.End.Insert("I'm happy to see you!", New CharacterFormat() With {
				.Size = 20,
				.FontColor = Color.DarkGreen,
				.UnderlineStyle = UnderlineType.Single
			})

			' Save PDF to a file
			dc.Save(pdfPath, New PdfSaveOptions())

			' Create a new process: Acrobat Reader. You may change in on Foxit Reader.
			Dim processFilename As String = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("Software").OpenSubKey("Microsoft").OpenSubKey("Windows").OpenSubKey("CurrentVersion").OpenSubKey("App Paths").OpenSubKey("Acrobat.exe").GetValue(String.Empty).ToString()

			' Let's transfer our PDF file to the process Adobe Reader
			Dim info As New ProcessStartInfo()
			info.Verb = "print"
			info.FileName = processFilename
			info.Arguments = String.Format("/p /h {0}", pdfPath)
			info.CreateNoWindow = True

			'(It won't be hidden anyway... thanks Adobe!)
			info.WindowStyle = ProcessWindowStyle.Hidden
			info.UseShellExecute = False

			Dim p As Process = Process.Start(info)
			p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden

			' Print our PDF
			Dim counter As Integer = 0
			Do While Not p.HasExited
				System.Threading.Thread.Sleep(1000)
				counter += 1
				If counter = 5 Then
					Exit Do
				End If
			Loop
			If Not p.HasExited Then
				p.CloseMainWindow()
				p.Kill()
			End If

			' Open the result for demonstration purposes.
			System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(pdfPath) With {.UseShellExecute = True})
		End Sub
	End Class
End Namespace

Download


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу support@sautinsoft.com или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



Вопросы и предложения всегда приветствуются!

Мы разрабатываем компоненты .Net с 2002 года. Мы знаем форматы PDF, DOCX, RTF, HTML, XLSX и Images. Если вам нужна помощь в создании, изменении или преобразовании документов в различных форматах, мы можем вам помочь. Мы напишем для вас любой пример кода абсолютно бесплатно.