使用IRONPDF C#文本到PDF(代碼示例教程) Curtis Chau 更新日期:8月 21, 2025 Download IronPDF NuGet 下載 DLL 下載 Windows 安裝程式 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article Over the past few years, the use of .NET Technology has increased rapidly, especially following the release of .NET Core, which ultimately increased the use of the C# programming language. It is therefore now essential that any C# programmer learns how to convert text into PDF files. There are multiple use cases where it is needed to convert text into PDFs. Making Reports Converting Invoices into PDF Making a Text Editor Creating Fillable PDF Forms Converting text files into PDF files ...and many more. It is necessary to have a third-party library to convert text into PDF documents. There are multiple options on the market, but some are paid, some are difficult to use, and some have performance issues. There is a library that is free for development and easy to use, so much so that all it takes is just one line of code to convert text into PDF. It also provides higher performance levels. This library is IronPDF. IronPDF is supported by all .NET Frameworks. It is developer-friendly and provides a variety of features in a single library, including creating PDFs from URLs, creating PDFs from text, converting HTML files to PDF files, and many more. Let's take a look at an example of how to convert text to PDF. How to Convert TXT to PDF in C# Install C# library to convert TXT file to PDF Use RenderHtmlAsPdf method to convert string to PDF Read the TXT file with ReadAllText method and pass it to RenderHtmlAsPdf to generate PDF Add customized watermark to the PDF Send the newly generated PDF to the default printer with Print method Create a Visual Studio Project Open Microsoft Visual Studio. Click on Create New Project. Select the template "Console Application" for simplicity, but you can use Windows Forms, ASP.NET Web Forms, MVC, Web APIs, or any template as per your needs. Select Next, Name the Project, Select Target Framework, and press Create. A new console project will be created. Create a new Console Application in Visual Studio Next, install the NuGet Package for IronPDF. IronPDF is a .NET library for generating, reading, editing, and saving PDF files in .NET projects. IronPDF features HTML-to-PDF for .NET 5 Core, Standard, and Framework, with full HTML-to-PDF support including CSS3 and JS. Install the NuGet Package To install the IronPDF NuGet Package, go to Tools > NuGet Package Manager > Package Manager Console. The following window will appear: Package Manager Console Next, write the following command in the Package Manager Console. Install-Package IronPdf Press Enter. Installation progress in the Package Manager Console This will install the IronPDF library to be able to use all the functionalities provided by this library anywhere in the project. Convert Text to PDF Next, let's address the main task here --- converting C# text into a PDF file. Firstly, reference the IronPDF library in the program.cs file. Write the following code snippet at the top of the file. using IronPdf; using IronPdf; Imports IronPdf $vbLabelText $csharpLabel Next, write the following code inside the main function. This code will convert text to PDF. // Create an instance of ChromePdfRenderer, which is responsible for rendering HTML into PDF ChromePdfRenderer renderer = new ChromePdfRenderer(); // Render a simple HTML string as a PDF document PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>This is my PDF</h1><p>This is generated for the tutorial of C# txt to PDF</p>"); // Save the generated PDF document to a specified path pdf.SaveAs(@"D:\Iron Software\textToPDF\myFirstPDF.pdf"); // Create an instance of ChromePdfRenderer, which is responsible for rendering HTML into PDF ChromePdfRenderer renderer = new ChromePdfRenderer(); // Render a simple HTML string as a PDF document PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>This is my PDF</h1><p>This is generated for the tutorial of C# txt to PDF</p>"); // Save the generated PDF document to a specified path pdf.SaveAs(@"D:\Iron Software\textToPDF\myFirstPDF.pdf"); ' Create an instance of ChromePdfRenderer, which is responsible for rendering HTML into PDF Dim renderer As New ChromePdfRenderer() ' Render a simple HTML string as a PDF document Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>This is my PDF</h1><p>This is generated for the tutorial of C# txt to PDF</p>") ' Save the generated PDF document to a specified path pdf.SaveAs("D:\Iron Software\textToPDF\myFirstPDF.pdf") $vbLabelText $csharpLabel Code Explanation Firstly, create the object of the ChromePdfRenderer. This object is responsible for converting text to PDF. In the second line, the RenderHtmlAsPdf function is called with the reference of the renderer object. This will generate a PDF from the text passed in the argument of this function. That PDF will then be temporarily stored as a PDF Document type. Finally, the newly generated PDF file is saved to the local drive using the SaveAs function. Pass the path as an argument in the SaveAs function. Output This is the output of the above code. It is very easy to generate PDF programmatically from text. The output PDF file from the code sample TXT File to PDF file In the above example, it shows how to convert simple TXT to PDF. Now, this example will demonstrate how to convert a text document into a PDF document. Given a sample source TXT file as shown below. The sample TXT file The following code will convert a text file to PDF. First, add the following namespace: using System.IO; using System.IO; Imports System.IO $vbLabelText $csharpLabel Write the following code snippet inside the main function. // Read all text from a TXT file into a string string text = File.ReadAllText(@"D:\Iron Software\textToPDF\myTxtFile.txt"); // Use the ChromePdfRenderer to render the text as a PDF document ChromePdfRenderer renderer = new ChromePdfRenderer(); PdfDocument pdf = renderer.RenderHtmlAsPdf(text); // Save the resulting PDF file to a specified location pdf.SaveAs(@"D:\Iron Software\textToPDF\textFileToPDF.pdf"); // Read all text from a TXT file into a string string text = File.ReadAllText(@"D:\Iron Software\textToPDF\myTxtFile.txt"); // Use the ChromePdfRenderer to render the text as a PDF document ChromePdfRenderer renderer = new ChromePdfRenderer(); PdfDocument pdf = renderer.RenderHtmlAsPdf(text); // Save the resulting PDF file to a specified location pdf.SaveAs(@"D:\Iron Software\textToPDF\textFileToPDF.pdf"); ' Read all text from a TXT file into a string Dim text As String = File.ReadAllText("D:\Iron Software\textToPDF\myTxtFile.txt") ' Use the ChromePdfRenderer to render the text as a PDF document Dim renderer As New ChromePdfRenderer() Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(text) ' Save the resulting PDF file to a specified location pdf.SaveAs("D:\Iron Software\textToPDF\textFileToPDF.pdf") $vbLabelText $csharpLabel File.ReadAllText will read all the text from the file specified in the argument of the function. This text is then held in a string variable. This variable is then passed as an argument of the RenderHtmlAsPdf function. This function will convert text into a PDF document. Finally, specify the output filename in the SaveAs function. Output The output PDF file from a TXT file In the above example, it is very easy to convert text into a new PDF document. Add Watermark Let's add a watermark to this newly created PDF. Watermarks can help to avoid the misuse of documents. You can set your watermark as per your needs. Let's consider the following example: // Apply a watermark to the PDF with specified text and layout properties pdf.ApplyWatermark("<h1>my Watermark</h1>", 45, 45, IronPdf.Editing.VerticalAlignment.Top, IronPdf.Editing.HorizontalAlignment.Center); // Save the PDF with the watermark applied pdf.SaveAs(@"D:\Iron Software\textToPDF\myFirstPDF.pdf"); // Apply a watermark to the PDF with specified text and layout properties pdf.ApplyWatermark("<h1>my Watermark</h1>", 45, 45, IronPdf.Editing.VerticalAlignment.Top, IronPdf.Editing.HorizontalAlignment.Center); // Save the PDF with the watermark applied pdf.SaveAs(@"D:\Iron Software\textToPDF\myFirstPDF.pdf"); ' Apply a watermark to the PDF with specified text and layout properties pdf.ApplyWatermark("<h1>my Watermark</h1>", 45, 45, IronPdf.Editing.VerticalAlignment.Top, IronPdf.Editing.HorizontalAlignment.Center) ' Save the PDF with the watermark applied pdf.SaveAs("D:\Iron Software\textToPDF\myFirstPDF.pdf") $vbLabelText $csharpLabel The pdf variable holds a PdfDocument type. The ApplyWatermark function will add a watermark to the document. Pass your watermark text as an argument of the function such as "my watermark" as an example. The second argument is the watermark's rotation angle. The third and fourth arguments specify the vertical and horizontal alignment of the watermark. Output The following is the output generated by the sample code: The PDF file with the watermark in the center Print a PDF Document Printing a PDF document using IronPDF is very easy --- just write the following line of code: // Print the PDF document to the default printer pdf.Print(); // Print the PDF document to the default printer pdf.Print(); ' Print the PDF document to the default printer pdf.Print() $vbLabelText $csharpLabel This will print a PDF document on your default printer. There are multiple printer settings available, and you can choose as per your requirements. For more details regarding PDF print settings, please refer to this PDF Printing Guide. Summary This tutorial showed a very easy way to convert text into a PDF file with step-by-step examples and code explanations: convert text to PDF, generate a PDF from a TXT file, and print this PDF file. Moreover, it covered how to add watermarks to the documents. There are multiple useful and interesting features provided by IronPDF such as rendering charts in PDFs, adding barcodes, enhancing security with passwords, and even handling PDF forms, but it is impossible to cover them all here. For more details, please visit the IronPDF Feature Overview. IronPDF is a part of the Iron Software Suite. The suite includes an array of interesting products including IronXL, IronBarcode, IronOCR, and IronWebScraper. It is assured that you will find all of these products helpful. You can save up to 250% by purchasing the complete Iron Suite, as you can currently get all five products for the price of just two. For more details, please check the Iron Software Suite Pricing. Extracting Text with IronOCR into Searchable PDFs Another method for creating PDF documents from provided text would be to make use of the IronOCR library to extract text from scanned documents and images, and then use the extracted content to create a new PDF document. So why do this instead of simply using the scanned document? Scanned documents are not easy to modify or search, as they are still just images, only with text instead of pictures. So how would you create searchable PDFs, what exactly is IronOCR, and how could we make it work with IronPDF? Let’s take a look at how each of these questions can be answered. IronOCR: What is it? IronOCR is a powerful .NET library that lets developers like yourself perform OCR tasks with ease on provided images, scanned documents, and even specialized formats such as passports and license plates. In addition to powerful OCR capabilities, IronOCR also provides the tools to refine your images if they need to be edited in order to be easier scanned. These editing tools include the DeNoise(), Sharpen() and Deskew(), to name a few. Extracting Text with IronOCR Now, let’s take a look at how you can extract text from scanned documents and turn it into a searchable PDF that can then be used and edited by IronPDF. First, we’ll take a scanned document, like the one below, and load it into our code. using IronOcr; class Program { static void Main(string[] args) { // Create an instance of the OCR Tesseract var ocr = new IronTesseract(); // Enable searchable PDF output ocr.Configuration.RenderSearchablePdf = true; // Load a scanned document image using var input = new OcrInput(); input.LoadImage("sample-page.png"); // Perform OCR on the scanned document OcrResult result = ocr.Read(input); // Output the recognized text Console.WriteLine(result.Text); // Save the recognized text to a file result.SaveAsSearchablePdf("output.pdf"); } } using IronOcr; class Program { static void Main(string[] args) { // Create an instance of the OCR Tesseract var ocr = new IronTesseract(); // Enable searchable PDF output ocr.Configuration.RenderSearchablePdf = true; // Load a scanned document image using var input = new OcrInput(); input.LoadImage("sample-page.png"); // Perform OCR on the scanned document OcrResult result = ocr.Read(input); // Output the recognized text Console.WriteLine(result.Text); // Save the recognized text to a file result.SaveAsSearchablePdf("output.pdf"); } } Imports IronOcr Friend Class Program Shared Sub Main(ByVal args() As String) ' Create an instance of the OCR Tesseract Dim ocr = New IronTesseract() ' Enable searchable PDF output ocr.Configuration.RenderSearchablePdf = True ' Load a scanned document image Dim input = New OcrInput() input.LoadImage("sample-page.png") ' Perform OCR on the scanned document Dim result As OcrResult = ocr.Read(input) ' Output the recognized text Console.WriteLine(result.Text) ' Save the recognized text to a file result.SaveAsSearchablePdf("output.pdf") End Sub End Class $vbLabelText $csharpLabel Output This creates a PDF document that maintains the original scanned document’s layout and styling, only now it is a searchable, easy-to-edit PDF document that can be used by IronPDF for further manipulation or sharing. IronPDF and IronOCR Licensing When working with powerful .NET libraries like IronPDF and IronOCR, developers often want clarity on how licensing works—especially in production environments. Both libraries follow IronSoftware’s straightforward licensing model, designed to support projects ranging from small prototypes to large-scale enterprise solutions. IronPDF Licensing IronPDF is licensed per developer with flexible deployment rights, meaning a single developer license covers unlimited usage across applications and servers. This makes it a cost-effective choice for teams that need to scale. Licenses are perpetual, so once purchased, they can be used indefinitely. Subscription options are also available for those who prefer annual renewals with updates and priority support included. Want to try before you buy? Try the IronPDF free trial to test out its robust set of features for yourself. IronOCR Licensing IronOCR follows the same simple licensing model as IronPDF, offering per-developer licenses with unlimited deployment rights. This makes it especially appealing for projects that require scalable OCR functionality, such as document digitization, automated text extraction, or searchable PDF generation. With IronOCR, licensing covers the entire suite of features, including support for 125+ languages, PDF text recognition, and advanced image-to-text conversions. Just like IronPDF, you can deploy to cloud services, containers, or enterprise servers without additional fees. Just like IronPDF, IronOCR also offers a free trial for developers looking to try it out for themselves before purchasing a licence. Why This Matters for Developers Many competing PDF and OCR solutions add complexity with runtime licensing, per-server fees, or feature-based tiers. IronSoftware keeps it simple: one developer license unlocks the full power of the library across all your projects. This lets you focus on coding and delivering features—not tracking usage limits or negotiating enterprise contracts. 常見問題解答 如何在C#中將文字轉換為PDF? 您可以使用 IronPDF 庫在 C# 中將文字轉換為 PDF。透過 NuGet 套件管理器安裝 IronPDF,然後使用ChromePdfRenderer類將 HTML 或純文字渲染為 PDF 文檔,並使用SaveAs方法儲存。 使用這種方法將文字轉換為 PDF 有什麼好處? 使用 IronPDF 將文字轉換為 PDF 具有高效能和易用性,並支援多種 .NET 框架。它將轉換過程簡化為幾行程式碼,使其成為建立報表、發票和可填寫表單的理想選擇。 如何在C#中為PDF添加浮水印? 若要在 C# 中為 PDF 新增浮水印,請使用 IronPDF 的ApplyWatermark方法,該方法應用於PdfDocument物件。您可以根據需要自訂浮水印的文字、旋轉角度和對齊方式。 我可以用C#列印PDF文件嗎? 是的,使用 IronPDF,您可以透過呼叫PdfDocument物件的Print方法來列印 PDF 文檔,該方法會將文檔傳送到您的預設印表機。 如何在 C# 中將 TXT 檔案轉換為 PDF? 要在 C# 中將 TXT 檔案轉換為 PDF,請使用File.ReadAllText讀取檔案中的文本,然後使用 IronPDF 的 ` ChromePdfRenderer將此文本渲染為 PDF 格式。最後,使用SaveAs方法儲存 PDF 檔案。 除了上述格式外,該函式庫還能進行哪些文件轉換? IronPDF 不僅可以處理文字到 PDF 的轉換,還可以渲染圖表、添加條碼、使用密碼保護文件以及處理 PDF 表單等功能。 如何在我的專案中安裝 IronPDF 庫? 若要在 Visual Studio 專案中安裝 IronPDF,請開啟Install-Package IronPdf 。這將把庫添加到您的項目中並啟用其功能。 我可以在哪裡了解更多關於IronPDF的功能? 若要了解 IronPDF 的更多功能,請造訪其網站上的 IronPDF 功能概述頁面,以取得詳細資訊和更多教學。 IronPDF 與 .NET 10 相容嗎?在 .NET 10 中使用 IronPDF 時有什麼特殊注意事項嗎? 是的,IronPDF 完全相容於 .NET 10。它開箱即用,無需任何額外配置。使用 .NET 10 時,您可以充分利用其效能提升、async/await 支援、現代化 API 和跨平台功能。對於文字轉 PDF 轉換,請確保引用最新的 IronPDF NuGet 套件,並像往常一樣在 .NET 10 專案中使用ChromePdfRenderer 。 Curtis Chau 立即與工程團隊聊天 技術作家 Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。 相關文章 發表日期 11月 13, 2025 如何在 C# 中合併兩個 PDF 位元組數組 使用 IronPDF 在 C# 中合併兩個 PDF 位元組數組。學習如何透過簡單的程式碼範例,將來自位元組數組、記憶體流和資料庫的多個 PDF 文件合併在一起。 閱讀更多 發表日期 11月 13, 2025 如何在 ASP.NET MVC 中創建 PDF 檢視器 為 ASP.NET MVC 應用程式構建一個強大的 PDF 檢視器。顯示 PDF 文件,將視圖轉換為 PDF,使用 IronPDF 添加互動功能。 閱讀更多 發表日期 11月 13, 2025 如何建立 .NET HTML 轉 PDF 轉換器 學習如何在.NET中使用IronPDF將HTML轉換為PDF。 閱讀更多 如何使用C#將圖像轉換為PDF【代碼示例教程】C#將PNG轉換為PDF(代碼示例...
發表日期 11月 13, 2025 如何在 C# 中合併兩個 PDF 位元組數組 使用 IronPDF 在 C# 中合併兩個 PDF 位元組數組。學習如何透過簡單的程式碼範例,將來自位元組數組、記憶體流和資料庫的多個 PDF 文件合併在一起。 閱讀更多
發表日期 11月 13, 2025 如何在 ASP.NET MVC 中創建 PDF 檢視器 為 ASP.NET MVC 應用程式構建一個強大的 PDF 檢視器。顯示 PDF 文件,將視圖轉換為 PDF,使用 IronPDF 添加互動功能。 閱讀更多