如何創建新的PDF檔案
建立新的PDF是從頭開始生成全新的PDF文件,通常是通過程式化地添加文本、圖片或其他元素。 這可以使用像 IronPDF 這樣的庫在 C# 中完成,這使得開發人員能夠在將文件儲存為 PDF 檔案之前定義內容、佈局和格式。
How to Create New PDFs
- Download IronPDF from NuGet for creating new PDFs
- Use the PdfDocument constructor to create a blank PDF
- Import existing PDF from file, URL, byte, as well as JSON
- Convert many different formats to PDFs such as HTML, RTF, Markdown, images, and XML
- Export the PDF document
立即在您的專案中使用IronPDF,並享受免費試用。
建立空白 PDF 範例
有多種方式可以創建 PDF 對象。 讓我們從最簡單的方法開始,只需 PDF 的寬度和高度。 這個 PdfDocument 建構函數將創建一個新的空白 PDF,準備進行自訂和使用。
代碼
:path=/static-assets/pdf/content-code-examples/how-to/create-new-pdfs.cs
using IronPdf;
PdfDocument pdf = new PdfDocument(270, 270);
pdf.SaveAs("blankPage.pdf");
從文件匯入PDF
在 PDF 被修改或轉換之前,必須先作為 PdfDocument 物件導入。 使用 PdfDocument 類的靜態 FromFile
方法來完成此操作。 在相同的類別中,同樣也支援從 JSON、位元組陣列、數據流及網址匯入 PDF。
代碼
:path=/static-assets/pdf/content-code-examples/how-to/create-new-pdfs-from-file.cs
using IronPdf;
PdfDocument pdf = PdfDocument.FromFile("sample.pdf");
pdf.SaveAs("export.pdf");
從其他格式轉換
除了前面提到的獲取 PdfDocument 物件的方法之外,您還可以將各種格式轉換為 PDF。 最先進的方法是將 HTML 轉換為 PDF,這會使用 Chrome 引擎呈現 HTML 及其所有資產,包括 JavaScript、圖片、鏈接和 CSS 樣式。除了 HTML,您還可以將其他格式轉換為 PDF,例如圖片、RTF、Markdown 和 XML。
<!某些情況下,它的渲染效果與我們網站上不一致,例如,在我們的網站上,有些組件的背景是透明的。
代碼
:path=/static-assets/pdf/content-code-examples/how-to/create-new-pdfs-from-html.cs
using IronPdf;
// Instantiate Renderer
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.EnableJavaScript = true;
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
renderer.RenderingOptions.PaperFit.UseResponsiveCssRendering(1800);
renderer.RenderingOptions.WaitFor.RenderDelay(5000);
renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print;
// Create a PDF from a URL or local file path
var pdf = renderer.RenderUrlAsPdf("https://ironpdf.com/");
// Export to a file or Stream
pdf.SaveAs("url.pdf");
輸出 PDF
-->