푸터 콘텐츠로 바로가기
제품 비교
PDFsharp를 사용하여 C#(.NET 5)에서 PDF를 생성하는 방법

PDFSharp를 사용하여 C#(.NET 5)에서 PDF를 생성하는 방법

The video is an instructional guide on how to use the PDFsharp library to generate a PDF file using C# code. The speaker begins by introducing PDFsharp as a tricky but effective library for generating PDF files. The library has advanced features, and unlike many of its competitors, it is completely free. The speaker emphasizes that despite its complexity, PDFsharp is an excellent choice for generating PDF files using C#.

To begin the tutorial, the speaker presents an example of a generated PDF file that consists of three lines of text. The first line of text is not exactly the first one, while the third line of text appears at the bottom right-hand corner. The speaker notes that the order of the text will make sense once they delve into the code. They also explain that they will be using .NET 5 to demonstrate how PDFsharp works.

Install and Setup

Before getting into the code, the speaker highlights that setting up the environment for PDFsharp can be quite challenging. They explain that three NuGet packages must be installed before working with PDFsharp NuGet Package Details. The first package is PDFsharp itself, which may generate a warning that it may not match with .NET due to its older version. The other two packages are System.Drawing.Common and System.Text.Encoding.CodePages.

How to Generate PDF in C# (.NET 5) using PDFSharp: Figure 1

The speaker emphasizes that all three packages must be installed before working with PDFsharp; otherwise, the code will throw an error. They explain that the System.Text.Encoding.CodePages package is especially important as it provides the encoding support necessary for generating PDF files. The speaker also notes that failure to install the packages correctly could be difficult to troubleshoot.

To make PDFSharp work properly, the speaker explains that a provider must be registered for System.Text.Encoding. The provider comes from the System.Text.Encoding.CodePages package, and the speaker highlights the importance of registering the package to ensure that PDFsharp functions correctly. They explain that failing to register the provider will result in an error, which can be challenging to troubleshoot.

Creating a PDF File

Next, the speaker presents a simple console application that uses PDFsharp to generate a PDF file. They explain that before using the library, the using statements for PDFsharp Drawing and PDFsharp PDF must be declared. The speaker then presents the code to generate the PDF file, which involves creating a new document, adding a new page, and drawing the text on the page.

using PdfSharp.Drawing;
using PdfSharp.Pdf;

namespace PdfSharpExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a new PDF document
            PdfDocument document = new PdfDocument();
            // Add a new page
            PdfPage page = document.AddPage();
            // Prepare to draw on the page
            XGraphics gfx = XGraphics.FromPdfPage(page);
            // Define a font
            XFont font = new XFont("Verdana", 20, XFontStyle.Bold);

            // Draw a string to the page
            gfx.DrawString("Hello, PDFsharp!", font, XBrushes.Black,
                new XRect(0, 0, page.Width, page.Height),
                XStringFormats.Center);

            // Save the document
            const string filename = "HelloWorld.pdf";
            document.Save(filename);  
        }
    }
}
using PdfSharp.Drawing;
using PdfSharp.Pdf;

namespace PdfSharpExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a new PDF document
            PdfDocument document = new PdfDocument();
            // Add a new page
            PdfPage page = document.AddPage();
            // Prepare to draw on the page
            XGraphics gfx = XGraphics.FromPdfPage(page);
            // Define a font
            XFont font = new XFont("Verdana", 20, XFontStyle.Bold);

            // Draw a string to the page
            gfx.DrawString("Hello, PDFsharp!", font, XBrushes.Black,
                new XRect(0, 0, page.Width, page.Height),
                XStringFormats.Center);

            // Save the document
            const string filename = "HelloWorld.pdf";
            document.Save(filename);  
        }
    }
}
$vbLabelText   $csharpLabel

The speaker notes that the code for generating the PDF file can be adjusted to include more complex features, such as adding images, tables, and charts. They also explain that PDFsharp provides various features for working with fonts, including embedding fonts in the PDF file.

How to Generate PDF in C# (.NET 5) using PDFSharp: Figure 2

The speaker explains the importance of setting up the environment correctly by installing the necessary NuGet packages and registering a provider for System.Text.Encoding. They also present a simple console application that uses PDFsharp to generate a PDF file and demonstrate how the code can be adjusted to include more complex features. The video is an excellent resource for anyone interested in generating PDF files using C# and PDFsharp.

Creating Lists and More Complex Items

In the second part of the video, the speaker begins by introducing a more complex example of creating a PDF document. He emphasizes that it is pointless to have an empty PDF document and proceeds to explain how to create a new page using the PDFSharp library. He notes that the process is similar to creating things in Excel or PowerPoint add-ins, and that once the page is created, it works with a reference that does not require the invocation of another method.

How to Generate PDF in C# (.NET 5) using PDFSharp: Figure 3

The speaker then introduces the XGraphics variable, which provides methods to draw things like text, lines, and images. The XFont variable is also introduced as a means of setting up a font for use in the PDF document. The speaker notes that the font can be generated somewhere else, but that it is useful to set it up globally if there is a more complex arrangement.

Next, the speaker discusses the DrawString method, which writes text into the PDF file. He notes that the complex part of the method is determining where the text will be drawn and explains the various parameters involved, such as the font, color, and boundaries of where the text might align. He also explains the use of the XBrushes variable to set the color of the text.

Explaining DrawString and Other Methods

The speaker then presents several examples of using the DrawString method with different parameters, such as aligning the text in the center, aligning it at the bottom left, and specifying the exact coordinates where the text will be placed. He notes that the last option is the most customizable and offers a great deal of flexibility.

How to Generate PDF in C# (.NET 5) using PDFSharp: Figure 4

The speaker explains how to create a table using graphics in the C# programming language. They cover how to insert images, strings, and lines, as well as how to draw arcs and barcodes using the graphics feature. They also explain the importance of trial and error when working with coordinates and how to draw lines to separate rows.

The speaker also discusses the table header and the need for a starting point for values and the line. They explain how to adjust the y position and add rows of records, and how to move to another page when the table exceeds a certain number of records. Finally, they mention the importance of resetting values for each page.

Conclusion

In conclusion, the speaker emphasizes the importance of being familiar with Microsoft Office add-ins when working with PDFSharp and offers his own course on the topic. He also notes that the library is highly versatile and can be used to create a wide range of PDF documents, from simple text documents to more complex ones with images, graphics, and custom layouts.

IronPDF: A C# PDF Library

IronPDF is a C# PDF library for creating, editing, and manipulating PDF documents. It is designed to be easy to use and integrates with .NET applications seamlessly.

Compared to PDF Sharp, IronPDF offers several advantages. Firstly, it is a commercial product and comes with professional support, which is not available with PDF Sharp. Secondly, IronPDF has better documentation and a more intuitive API, making it easier for developers to get started and work with the library. Additionally, IronPDF has a richer set of features, including advanced PDF creation options and support for working with HTML, CSS, and JavaScript.

Features

Features IronPDF PDFSharp
Convert HTML to PDF Yes No
Professional support Yes No
HTML, CSS, and JavaScript Support Yes No
Digital signatures Yes No
Encryption Yes No

One of the key features of IronPDF is its ability to convert HTML to PDF using IronPDF, making it easy to create PDF documents from web pages. This feature is not available in PDF Sharp, which limits its use cases.

IronPDF also has support for digital signatures and encryption, which is crucial for sensitive documents that require secure handling. This feature is not available in PDF Sharp.

IronPDF is a more powerful and user-friendly PDF library compared to PDF Sharp, with additional features and better support options. However, it is also a commercial product, so it may not be the best choice for developers looking for a free or open-source solution.

참고해 주세요PDFsharp is a registered trademark of its respective owner. This site is not affiliated with, endorsed by, or sponsored by PDFsharp. All product names, logos, and brands are property of their respective owners. Comparisons are for informational purposes only and reflect publicly available information at the time of writing.

자주 묻는 질문

C#에서 PDFsharp를 사용하여 PDF 파일을 생성하려면 어떻게 해야 하나요?

PDFsharp를 사용하여 PDF를 생성하려면 새 PDF 문서를 만들고 페이지를 추가한 다음 X그래픽 개체를 사용하여 텍스트 또는 그래픽을 그려야 합니다. PdfSharp.DrawingPdfSharp.Pdf 네임스페이스에 대한 사용 문을 포함해야 합니다.

PDFsharp에 필요한 필수 NuGet 패키지는 무엇인가요?

PDFsharp로 효율적으로 작업하려면 다음 NuGet 패키지를 설치해야 합니다: PDFsharp, System.Drawing.Common 및 System.Text.Encoding.CodePages. 이러한 패키지는 인코딩 지원 및 적절한 PDF 생성을 위해 매우 중요합니다.

C#에서 PDF 생성을 위해 IronPDF와 PDFsharp를 어떻게 비교하나요?

IronPDF는 HTML을 PDF로 변환, 디지털 서명 및 암호화와 같은 고급 기능을 제공하는 상용 라이브러리로 PDFsharp에서는 사용할 수 없습니다. 또한 더 나은 문서화 및 전문가 지원을 제공하여 복잡한 작업에 더욱 사용자 친화적입니다.

PDF 생성에 PDFsharp를 사용할 때의 한계는 무엇인가요?

PDFsharp는 HTML, CSS 또는 JavaScript를 지원하지 않으므로 사용 사례가 제한됩니다. 복잡한 문서를 위한 인코딩 설정과 Microsoft Office 추가 기능에 대한 충분한 이해가 필요하므로 IronPDF에 비해 직관성이 떨어질 수 있습니다.

PDFsharp에 System.Text.Encoding.CodePages 패키지가 중요한 이유는 무엇인가요?

System.Text.Encoding.CodePages 패키지는 PDFsharp로 PDF 파일을 생성할 때 필요한 인코딩 지원을 제공합니다. 이 패키지를 올바르게 설치 및 등록하지 않으면 인코딩 관련 오류가 발생할 수 있습니다.

무료 C# 라이브러리를 사용하여 HTML을 PDF로 변환할 수 있나요?

아니요, PDFsharp는 HTML에서 PDF로의 변환을 지원하지 않습니다. 이러한 기능을 사용하려면 다른 고급 기능과 함께 이 기능을 제공하는 IronPDF와 같은 상용 라이브러리가 필요합니다.

PDFsharp의 일반적인 오류를 해결하려면 어떻게 해야 하나요?

PDFsharp에서 흔히 발생하는 오류는 NuGet 패키지의 잘못된 설정이나 인코딩 문제로 인해 발생하는 경우가 많습니다. 이러한 문제를 해결하려면 System.Text.Encoding.CodePages를 비롯한 모든 필수 패키지가 올바르게 설치 및 등록되었는지 확인하세요.

C# 개발자를 위한 IronPDF에는 어떤 고급 기능이 있나요?

IronPDF는 HTML을 PDF로 변환, 디지털 서명, 암호화, CSS 및 JavaScript 처리 기능과 같은 고급 기능을 제공합니다. 또한 .NET 애플리케이션과의 통합 및 전문가 지원도 제공하므로 개발자를 위한 강력한 도구입니다.

PDFsharp를 사용하여 PDF의 텍스트 레이아웃을 사용자 지정하려면 어떻게 해야 하나요?

PDFsharp를 사용하면 XGraphics 클래스의 DrawString 메서드를 활용하여 PDF의 텍스트 레이아웃을 사용자 지정할 수 있습니다. 이를 통해 지정된 경계 내에서 글꼴, 색상 및 텍스트 정렬과 같은 속성을 설정할 수 있습니다.

PDFsharp는 C#으로 복잡한 PDF 문서를 만드는 데 적합합니까?

PDFsharp는 복잡한 PDF 문서를 만들 수 있지만 인코딩 및 Microsoft Office 추가 기능에 대한 확실한 이해가 필요합니다. 보다 직관적인 API와 추가 기능으로 인해 복잡한 작업에는 IronPDF가 더 나은 옵션일 수 있습니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.