### Quick Start Example Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/SUMMARY.txt A basic example demonstrating the initial setup and import statements for using the Spire.PDF for Python library. ```APIDOC ## Quick Start Example ```python from spire.pdf import * from spire.pdf.common import * # Your PDF manipulation code here ``` ``` -------------------------------- ### Complete PDF Configuration Example Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/configuration.md A comprehensive example demonstrating the setup of a PDF document, including metadata, page creation, font and color configuration, and drawing text elements. Enables form creation. ```python from spire.pdf import * from spire.pdf.common import * # Create document doc = PdfDocument() # Configure metadata doc.DocumentInformation.Title = "Sample Form" doc.DocumentInformation.Author = "Developer" doc.DocumentInformation.Subject = "PDF Form Example" # Create page page = doc.Pages.Add(PdfPageSize.A4) cvas = page.Canvas # Configure fonts label_font = PdfFont(PdfFontFamily.Helvetica, 11.0, PdfFontStyle.Bold) normal_font = PdfFont(PdfFontFamily.Helvetica, 11.0) # Configure colors label_brush = PdfSolidBrush(PdfRGBColor(Color.get_Black())) border_color = PdfRGBColor(Color.get_DarkGray()) # Draw labels cvas.DrawString("Name:", label_font, label_brush, 50.0, 50.0) cvas.DrawString("Email:", label_font, label_brush, 50.0, 100.0) cvas.DrawString("Age:", label_font, label_brush, 50.0, 150.0) # Enable form creation doc.AllowCreateForm = True ``` -------------------------------- ### Complete PDF Form Creation Example Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/api-reference/FormFields.md A comprehensive example showing how to create a PDF document, add various form fields (TextBox, CheckBox, ListBox) with specific properties, and save the resulting PDF. ```python from spire.pdf import * from spire.pdf.common import * doc = PdfDocument() doc.LoadFromFile("template.pdf") doc.AllowCreateForm = True page = doc.Pages[0] font = PdfFont(PdfFontFamily.Helvetica, 11.0) # Add label canvas = page.Canvas brush = PdfSolidBrush(PdfRGBColor(Color.get_Black())) canvas.DrawString("Name:", font, brush, 50.0, 50.0) # Add text field textbox = PdfTextBoxField(page, "NameField") textbox.Bounds = RectangleF(150.0, 48.0, 200.0, 20.0) textbox.BorderWidth = 0.75 textbox.BorderStyle = PdfBorderStyle.Solid textbox.Font = font doc.Form.Fields.Add(textbox) # Add checkbox canvas.DrawString("Agree to terms:", font, brush, 50.0, 100.0) checkbox = PdfCheckBoxField(page, "AgreementCheck") checkbox.Bounds = RectangleF(200.0, 98.0, 20.0, 20.0) doc.Form.Fields.Add(checkbox) # Add list field canvas.DrawString("Country:", font, brush, 50.0, 150.0) listbox = PdfListBoxField(page, "CountryList") listbox.Bounds = RectangleF(150.0, 148.0, 200.0, 20.0) listbox.Items.Add(PdfListFieldItem("USA", "us")) listbox.Items.Add(PdfListFieldItem("UK", "uk")) listbox.Items.Add(PdfListFieldItem("Canada", "ca")) doc.Form.Fields.Add(listbox) doc.SaveToFile("form.pdf") doc.Close() ``` -------------------------------- ### Configure PDF Page Setup Options Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/Examples/pdf_python.md Demonstrates various page setup options including page size, margins, orientation, rotation, and background color. This allows for detailed customization of individual pages or sections within a PDF document. ```python # Create a pdf document doc = PdfDocument() # Set the margin unitCvtr = PdfUnitConvertor() margin = PdfMargins() margin.Top = unitCvtr.ConvertUnits( 2.54, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point) margin.Bottom = margin.Top margin.Left = unitCvtr.ConvertUnits( 3.17, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point) margin.Right = margin.Left # Create one page page = doc.Pages.Add(PdfPageSize.A4(), margin) page.BackgroundColor = Color.get_Chocolate() page = doc.Pages.Add(PdfPageSize.A4(), margin) page.BackgroundColor = Color.get_Coral() page = doc.Pages.Add(PdfPageSize.A3( ), margin, PdfPageRotateAngle.RotateAngle180, PdfPageOrientation.Landscape) page.BackgroundColor = Color.get_LightPink() # create section section = doc.Sections.Add() page = section.Pages.Add() section.PageSettings.Size = PdfPageSize.A4() section.PageSettings.Margins = margin # Set background color page = section.Pages.Add() page.BackgroundColor = Color.get_LightSkyBlue() ``` -------------------------------- ### Initialize PdfCanvas and Draw Text Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/api-reference/PdfCanvas.md Demonstrates how to get a PdfCanvas instance and draw basic text on a PDF page. Requires PdfDocument, PdfPage, PdfFont, and PdfSolidBrush setup. ```python doc = PdfDocument() page = doc.Pages.Add() canvas = page.Canvas # Draw text font = PdfFont(PdfFontFamily.Helvetica, 12.0) brush = PdfSolidBrush(PdfRGBColor(Color.get_Black())) canvas.DrawString("Hello", font, brush, 10.0, 10.0) ``` -------------------------------- ### Complete PDF Attachment Management Example Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/api-reference/Bookmarks_Attachments.md A comprehensive example demonstrating how to add multiple files as attachments, list existing attachments, and extract all attachments from a PDF document using Spire.PDF for Python. ```python from spire.pdf import * import os def add_attachments_to_pdf(pdf_file, attachments_list, output_file): """Add multiple files as attachments to a PDF.""" doc = PdfDocument() doc.LoadFromFile(pdf_file) for file_path in attachments_list: if os.path.exists(file_path): attachment = doc.Attachments.Add(file_path) print(f"Added attachment: {os.path.basename(file_path)}") else: print(f"File not found: {file_path}") doc.SaveToFile(output_file) print(f"Saved to {output_file} with {doc.Attachments.Count} attachments") doc.Close() def extract_attachments(pdf_file, output_dir): """Extract all attachments from a PDF.""" doc = PdfDocument() doc.LoadFromFile(pdf_file) if not os.path.exists(output_dir): os.makedirs(output_dir) for i in range(doc.Attachments.Count): attachment = doc.Attachments[i] # Save attachment output_path = os.path.join(output_dir, attachment.FileName) with open(output_path, "wb") as f: f.write(attachment.Data) print(f"Extracted: {attachment.FileName}") doc.Close() print(f"Extracted {doc.Attachments.Count} attachments to {output_dir}") def list_attachments(pdf_file): """List all attachments in a PDF.""" doc = PdfDocument() doc.LoadFromFile(pdf_file) if doc.Attachments.Count == 0: print("No attachments found") else: print(f"Found {doc.Attachments.Count} attachment(s):") for i in range(doc.Attachments.Count): attachment = doc.Attachments[i] print(f" {i + 1}. {attachment.FileName}") if attachment.Description: print(f" Description: {attachment.Description}") doc.Close() # Usage examples if __name__ == "__main__": # Add attachments files_to_attach = ["data.xlsx", "notes.txt", "image.png"] add_attachments_to_pdf("document.pdf", files_to_attach, "with_attachments.pdf") # List attachments list_attachments("with_attachments.pdf") # Extract attachments extract_attachments("with_attachments.pdf", "extracted/") ``` -------------------------------- ### Complete PDF Page Management Example Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/api-reference/PdfPageCollection.md A comprehensive example showing how to add, insert, draw on, remove, and save a PDF document using various PdfPageCollection methods. ```python from spire.pdf import * from spire.pdf.common import * doc = PdfDocument() # Add pages with different methods page1 = doc.Pages.Add(PdfPageSize.A4) page2 = doc.Pages.Add(612.0, 792.0) # Custom size # Insert a page page3 = doc.Pages.Insert(1, PdfPageSize.Letter) # Draw on each page font = PdfFont(PdfFontFamily.Helvetica, 12.0) brush = PdfSolidBrush(PdfRGBColor(Color.get_Black())) for i in range(doc.Pages.Count): page = doc.Pages[i] page.Canvas.DrawString(f"Page {i + 1}", font, brush, 10.0, 10.0) # Remove a page doc.Pages.RemoveAt(1) # Save document doc.SaveToFile("pages.pdf") doc.Close() ``` -------------------------------- ### PointF Example Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/types.md Shows how to create PointF objects for use in annotations or transformations. ```python point = PointF(100.0, 200.0) start = PointF(10.0, 10.0) end = PointF(100.0, 100.0) ``` -------------------------------- ### Complete Color and Brush Example Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/api-reference/Colors_Brushes_Pens.md Demonstrates creating and using solid, custom RGB, and gradient brushes, as well as predefined pens. ```APIDOC ## Complete Color and Brush Example ```python from spire.pdf import * from spire.pdf.common import * doc = PdfDocument() page = doc.Pages.Add() canvas = page.Canvas # Solid colors red_brush = PdfSolidBrush(PdfRGBColor(Color.get_Red())) blue_pen = PdfPen(PdfRGBColor(Color.get_Blue()), 2.0) # Custom RGB color custom_color = PdfRGBColor(Color.FromArgb(200, 100, 50)) custom_brush = PdfSolidBrush(custom_color) # Gradient brush gradient = PdfLinearGradientBrush( PointF(10.0, 10.0), PointF(110.0, 110.0), PdfRGBColor(Color.get_White()), PdfRGBColor(Color.get_Black()) ) # Draw shapes canvas.DrawRectangle(red_brush, 10.0, 10.0, 100.0, 100.0) canvas.DrawEllipse(blue_pen, 10.0, 120.0, 100.0, 100.0) canvas.DrawRectangle(gradient, 120.0, 10.0, 100.0, 100.0) # Predefined helpers canvas.DrawLine(PdfPens.get_Green(), 10.0, 230.0, 220.0, 230.0) doc.SaveToFile("colors.pdf") doc.Close() ``` **Import:** `from spire.pdf.common import Color; from spire.pdf import PdfRGBColor, PdfSolidBrush, PdfLinearGradientBrush, PdfRadialGradientBrush, PdfPen, PdfBrushes, PdfPens` **Location:** `spire.pdf` and `spire.pdf.common` modules ``` -------------------------------- ### Complete Bookmark Example Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/api-reference/Bookmarks_Attachments.md Demonstrates the creation of a complex, hierarchical bookmark structure within a PDF document. ```APIDOC ## Complete Bookmark Example ### Description This example demonstrates how to create a PDF document with a multi-level bookmark structure, including root bookmarks, child bookmarks, and formatting options like bold text and custom colors. ### Code ```python from spire.pdf import * from spire.pdf.common import * doc = PdfDocument() doc.LoadFromFile("input.pdf") # Create root bookmarks dest_ch1 = PdfDestination(doc.Pages[0]) ch1 = doc.Bookmarks.Add("Chapter 1", dest_ch1) dest_ch2 = PdfDestination(doc.Pages[5]) ch2 = doc.Bookmarks.Add("Chapter 2", dest_ch2) dest_ch3 = PdfDestination(doc.Pages[10]) ch3 = doc.Bookmarks.Add("Chapter 3", dest_ch3) # Add child bookmarks to Chapter 1 children_ch1 = ch1.GetChildBookmarks() dest_1_1 = PdfDestination(doc.Pages[1]) sec1_1 = children_ch1.Add("Section 1.1", dest_1_1) dest_1_2 = PdfDestination(doc.Pages[3]) sec1_2 = children_ch1.Add("Section 1.2", dest_1_2) # Add child bookmarks to Chapter 2 children_ch2 = ch2.GetChildBookmarks() dest_2_1 = PdfDestination(doc.Pages[6]) sec2_1 = children_ch2.Add("Section 2.1", dest_2_1) dest_2_2 = PdfDestination(doc.Pages[8]) sec2_2 = children_ch2.Add("Section 2.2", dest_2_2) # Format some bookmarks ch1.Bold = True ch1.Color = PdfRGBColor(Color.get_Blue()) ch2.Bold = True ch2.Color = PdfRGBColor(Color.get_DarkBlue()) doc.SaveToFile("bookmarked_document.pdf") doc.Close() ``` ``` -------------------------------- ### Color Class Example Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/types.md Demonstrates creating Color objects using predefined static methods and factory methods for custom colors. ```python red = Color.get_Red() custom = Color.FromArgb(255, 100, 50) semi_transparent = Color.FromArgb(128, 0, 0, 255) ``` -------------------------------- ### Complete PDF Drawing Example Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/api-reference/Shapes_Drawing.md This comprehensive example demonstrates drawing various shapes including rectangles, ellipses, pie charts, and paths using different pens, brushes, and gradients. It also shows how to save the result to a PDF file. Ensure all necessary imports are included. ```python from spire.pdf import * from spire.pdf.common import * import math doc = PdfDocument() page = doc.Pages.Add(PdfPageSize.A4) canvas = page.Canvas # Create pens and brushes black_pen = PdfPen(PdfRGBColor(Color.get_Black()), 1.0) red_pen = PdfPen(PdfRGBColor(Color.get_Red()), 2.0) blue_brush = PdfSolidBrush(PdfRGBColor(Color.get_LightBlue())) gradient_brush = PdfLinearGradientBrush( PointF(100.0, 100.0), PointF(300.0, 300.0), PdfRGBColor(Color.get_White()), PdfRGBColor(Color.get_DarkBlue()) ) # Draw various shapes canvas.DrawRectangle(blue_brush, 50.0, 50.0, 200.0, 150.0) canvas.DrawEllipse(red_pen, 300.0, 50.0, 150.0, 150.0) # Draw pie chart canvas.DrawPie(PdfSolidBrush(PdfRGBColor(Color.get_Yellow())), 50.0, 250.0, 100.0, 100.0, 0.0, 90.0) canvas.DrawPie(PdfSolidBrush(PdfRGBColor(Color.get_Red())), 50.0, 250.0, 100.0, 100.0, 90.0, 180.0) canvas.DrawPie(PdfSolidBrush(PdfRGBColor(Color.get_Green())), 50.0, 250.0, 100.0, 100.0, 270.0, 90.0) # Draw path path = PdfPath() path.AddLine(300.0, 250.0, 350.0, 280.0) path.AddLine(350.0, 280.0, 400.0, 250.0) path.AddLine(400.0, 250.0, 350.0, 220.0) path.Close() canvas.DrawPath(gradient_brush, path) doc.SaveToFile("shapes.pdf") doc.Close() ``` -------------------------------- ### RectangleF Example Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/types.md Demonstrates how to create and use a RectangleF object to define an area. ```python bounds = RectangleF(10.0, 20.0, 100.0, 50.0) ``` -------------------------------- ### Create and Format Hierarchical Bookmarks Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/api-reference/Bookmarks_Attachments.md A comprehensive example showing how to create root and nested bookmarks, set their destinations, and apply formatting like bold and color. ```python from spire.pdf import * from spire.pdf.common import * doc = PdfDocument() doc.LoadFromFile("input.pdf") # Create root bookmarks dest_ch1 = PdfDestination(doc.Pages[0]) ch1 = doc.Bookmarks.Add("Chapter 1", dest_ch1) dest_ch2 = PdfDestination(doc.Pages[5]) ch2 = doc.Bookmarks.Add("Chapter 2", dest_ch2) dest_ch3 = PdfDestination(doc.Pages[10]) ch3 = doc.Bookmarks.Add("Chapter 3", dest_ch3) # Add child bookmarks to Chapter 1 children_ch1 = ch1.GetChildBookmarks() dest_1_1 = PdfDestination(doc.Pages[1]) sec1_1 = children_ch1.Add("Section 1.1", dest_1_1) dest_1_2 = PdfDestination(doc.Pages[3]) sec1_2 = children_ch1.Add("Section 1.2", dest_1_2) # Add child bookmarks to Chapter 2 children_ch2 = ch2.GetChildBookmarks() dest_2_1 = PdfDestination(doc.Pages[6]) sec2_1 = children_ch2.Add("Section 2.1", dest_2_1) dest_2_2 = PdfDestination(doc.Pages[8]) sec2_2 = children_ch2.Add("Section 2.2", dest_2_2) # Format some bookmarks ch1.Bold = True ch1.Color = PdfRGBColor(Color.get_Blue()) ch2.Bold = True ch2.Color = PdfRGBColor(Color.get_DarkBlue()) doc.SaveToFile("bookmarked_document.pdf") doc.Close() ``` -------------------------------- ### PdfStringFormat Example Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/types.md Illustrates creating a PdfStringFormat object with custom alignment and word wrapping settings. ```python format = PdfStringFormat( PdfTextAlignment.Center, PdfVerticalAlignment.Middle, wordWrap=True ) ``` -------------------------------- ### Check if PDF is a Portfolio Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/Examples/pdf_python.md This example shows how to load a PDF document and check if it is a PDF portfolio. ```python # Create a pdf document doc = PdfDocument() # Load from file doc.LoadFromFile(inputFile) # Judge whether the document is portfolio or not value = doc.IsPortfolio if value: builder = "The document is portfolio" else: builder = "The document is not portfolio" ``` -------------------------------- ### Combine PDF Font Styles Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/types.md Example demonstrating how to combine multiple font styles using the bitwise OR operator. ```python PdfFontStyle.Bold | PdfFontStyle.Italic | PdfFontStyle.Underline ``` -------------------------------- ### Add Attachments to PDF Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/Examples/pdf_python.md This example demonstrates how to add multiple file attachments to a PDF document. ```python # Open pdf document doc = PdfDocument() doc.LoadFromFile(inputFile1) # Load files and add in attachments data = Stream(inputFileImg) attach1 = PdfAttachment("attachment1.png", data) data2 = Stream(inputFile2) attach2 = PdfAttachment("attachment2.pdf", data2) doc.Attachments.Add(attach1) doc.Attachments.Add(attach2) doc.SaveToFile(outputFile, FileFormat.PDF) doc.Close() ``` -------------------------------- ### Create a new PdfDocument instance Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/api-reference/PdfDocument.md Instantiate the PdfDocument class to create a new PDF document. This is the starting point for most PDF operations. ```python from spire.pdf import * doc = PdfDocument() page = doc.Pages.Add() doc.SaveToFile("output.pdf") doc.Close() ``` -------------------------------- ### Create PdfFont with Times Family Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/api-reference/PdfFont.md Example of creating a PdfFont instance using the Times font family and a specified size. ```python font = PdfFont(PdfFontFamily.Times, 14.0) ``` -------------------------------- ### Initialize Standard PDF Fonts Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/configuration.md Initializes standard PDF fonts like Helvetica, Times, and Courier with a specified size. These fonts do not require installation. ```python font = PdfFont(PdfFontFamily.Helvetica, 12.0) font = PdfFont(PdfFontFamily.Times, 12.0) font = PdfFont(PdfFontFamily.Courier, 12.0) ``` -------------------------------- ### Create and Add PdfListFieldItem Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/types.md Example of creating a PdfListFieldItem and adding it to a list box. Ensure the listbox object is properly initialized. ```python item = PdfListFieldItem("Display Text", "internal_value") listbox.Items.Add(item) ``` -------------------------------- ### Manage Child Bookmarks Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/api-reference/Bookmarks_Attachments.md Demonstrates how to get, add, and manage child bookmarks to create hierarchical bookmark structures within a PDF document. ```python # Get child bookmarks children = parent_bookmark.GetChildBookmarks() # Add child bookmark child_dest = PdfDestination(doc.Pages[2]) child = children.Add("Section 1.1", child_dest) # Nested structure grandchild_dest = PdfDestination(doc.Pages[3]) grandchildren = child.GetChildBookmarks() grandchild = grandchildren.Add("Section 1.1.1", grandchild_dest) ``` -------------------------------- ### Create PdfDestination and Link Annotation Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/types.md Example of creating a PdfDestination for a specific page and using it to create a document link annotation. Requires a PdfPageBase object and bounds. ```python destination = PdfDestination(doc.Pages[5]) link = PdfDocumentLinkAnnotation(bounds, destination) ``` -------------------------------- ### Wrap Text Around an Image in PDF Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/Examples/pdf_python.md This example demonstrates how to draw an image and then wrap text around it by calculating available space and using PdfStringLayouter. ```python # Creates a pdf document doc = PdfDocument() # Creates a page page = doc.Pages.Add() #Gets page width pageWidth = page.Canvas.ClientSize.Width y = 0.0 # Creates a brush brush = PdfSolidBrush(PdfRGBColor(Color.get_Black())) # Defines fonts font1 = PdfTrueTypeFont("Arial", 20.0, PdfFontStyle.Bold ,True) font2 = PdfTrueTypeFont("Arial", 16.0 , PdfFontStyle.Regular, True) # Defines text formats format1 = PdfStringFormat(PdfTextAlignment.Center) format1.CharacterSpacing = 1.0 format2 = PdfStringFormat() format2.LineSpacing = font2.Size * 1.5 # Draw title text text = "Spire.PDF for Python" page.Canvas.DrawString(text, font1, brush, pageWidth / 2, y, format1) size = font1.MeasureString(text, format1) y = y + size.Height + 6 # Draw image (assuming image is loaded) page.Canvas.DrawImage(image, PointF(pageWidth - image.PhysicalDimension.Width, y)) imageLeftSpace = pageWidth - image.PhysicalDimension.Width - 2 imageBottom = image.PhysicalDimension.Height + y # Layout text around image textLayouter = PdfStringLayouter() imageLeftBlockHeight = imageBottom - y result = textLayouter.Layout(text, font2, format2, SizeF(imageLeftSpace, imageLeftBlockHeight)) if result.ActualSize.Height < imageLeftBlockHeight: imageLeftBlockHeight = imageLeftBlockHeight + result.LineHeight result = textLayouter.Layout(text, font2, format2, SizeF(imageLeftSpace, imageLeftBlockHeight)) # Draw text lines around image for line in result.Lines: page.Canvas.DrawString(line.Text, font2, brush, 0.0, y, format2) y = y + result.LineHeight # Draw remaining text textWidget = PdfTextWidget(result.Remainder, font2, brush) textLayout = PdfTextLayout() textLayout.Break = PdfLayoutBreakType.FitPage textLayout.Layout = PdfLayoutType.Paginate bounds = RectangleF(PointF(0.0, y), page.Canvas.ClientSize) textWidget.StringFormat = format2 textWidget.Draw(page, bounds, textLayout) ``` -------------------------------- ### Create an empty PdfPath Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/api-reference/Shapes_Drawing.md Instantiate a PdfPath object to begin defining a custom path. This is the starting point for adding lines, curves, or other segments. ```python from spire.pdf import * from spire.pdf.common import * doc = PdfDocument() page = doc.Pages.Add() canvas = page.Canvas # Create a path path = PdfPath() ``` -------------------------------- ### Extract Highlighted Text from PDF Page Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/Examples/pdf_python.md This example demonstrates how to extract text from highlighted annotations on a PDF page. It iterates through annotations, identifies text markup annotations, and uses PdfTextExtractor to get the highlighted text based on the annotation's bounds. ```python # Create a pdf document doc = PdfDocument() # Get the first page page = doc.Pages[0] textMarkupAnnotation = None stringBuilder = "Extracted hightlighted text:" + '\n' # Get the annotation Collection from the document. annotations = page.AnnotationsWidget # Update free text annotation. if annotations.Count > 0: for i in range(annotations.Count): textMarkupAnnotation = annotations.get_Item(i) if isinstance(textMarkupAnnotation, PdfTextMarkupAnnotationWidget): # Get the highlighted text pdfTextExtractor=PdfTextExtractor(page) pdfTextExtractOptions=PdfTextExtractOptions() pdfTextExtractOptions.ExtractArea=textMarkupAnnotation.Bounds stringBuilder+=pdfTextExtractor.ExtractText(pdfTextExtractOptions)+ '\n' # Get the highlighted color color = textMarkupAnnotation.TextMarkupColor ``` -------------------------------- ### Create PdfLinearGradientBrush Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/api-reference/Colors_Brushes_Pens.md Define a linear gradient brush with specified start and end points, and start and end colors, then use it to draw a rectangle. ```python start = PointF(10.0, 10.0) end = PointF(110.0, 110.0) start_color = PdfRGBColor(Color.get_Red()) end_color = PdfRGBColor(Color.get_Blue()) gradient_brush = PdfLinearGradientBrush(start, end, start_color, end_color) canvas.DrawRectangle(gradient_brush, 10.0, 10.0, 100.0, 100.0) ``` -------------------------------- ### Complete PDF Creation with Multiple Fonts Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/api-reference/PdfFont.md A comprehensive example demonstrating the creation of a PDF document, adding a page, creating various fonts (regular, bold, italic), setting up a brush, drawing strings with different fonts, measuring text, and saving the PDF. ```python from spire.pdf import * from spire.pdf.common import * doc = PdfDocument() page = doc.Pages.Add() cavas = page.Canvas # Create different fonts regular_font = PdfFont(PdfFontFamily.Helvetica, 12.0) bold_font = PdfFont(PdfFontFamily.Helvetica, 12.0, PdfFontStyle.Bold) italic_font = PdfFont(PdfFontFamily.Times, 14.0, PdfFontStyle.Italic) # Create brush for text brush = PdfSolidBrush(PdfRGBColor(Color.get_Black())) # Draw text with different fonts canvas.DrawString("Regular text", regular_font, brush, 10.0, 10.0) canvas.DrawString("Bold text", bold_font, brush, 10.0, 30.0) canvas.DrawString("Italic text", italic_font, brush, 10.0, 50.0) # Measure text size = regular_font.MeasureString("Hello") print(f"Text size: {size.Width}x{size.Height}") doc.SaveToFile("fonts.pdf") doc.Close() ``` -------------------------------- ### Name Property Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/api-reference/PdfFont.md Gets the name of the font. ```APIDOC ## Name Property ### Description The name of the font. ### Type `str` ### Example ```python font = PdfFont(PdfFontFamily.Helvetica, 12.0) print(font.Name) # Output: Helvetica ``` ``` -------------------------------- ### Create PDF List with Custom Image Marker Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/Examples/pdf_python.md This example shows how to create a PDF document and add a page. It then initializes a PdfMarker object with a custom image style and sets a specific image file to be used as the marker for list items. ```python # Create a new PdfDocument doc = PdfDocument() # Add a new page to the document page = doc.Pages.Add() # Create a PdfMarker object with a custom image marker style marker = PdfMarker(PdfUnorderedMarkerStyle.CustomImage) # Set the image for the marker marker.Image = PdfImage.FromFile(inputFile_Img) ``` -------------------------------- ### PdfAttachment.Description Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/api-reference/Bookmarks_Attachments.md Gets or sets an optional description for the attachment. ```APIDOC ## PdfAttachment.Description ### Description Gets or sets an optional description for the attachment. ### Property Type str ### Example ```python attachment.Description = "Supporting documentation" ``` ``` -------------------------------- ### PdfAttachment.FileName Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/api-reference/Bookmarks_Attachments.md Gets or sets the name of the attached file. ```APIDOC ## PdfAttachment.FileName ### Description Gets or sets the name of the attached file. ### Property Type str ### Example ```python name = attachment.FileName print(f"Attached file: {name}") ``` ``` -------------------------------- ### Create a Simple PDF Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/README.md This snippet demonstrates how to create a new PDF document, add a page, draw "Hello, World!" text on it, and save the document. ```python from spire.pdf import * from spire.pdf.common import * doc = PdfDocument() page = doc.Pages.Add() font = PdfFont(PdfFontFamily.Helvetica, 12.0) brush = PdfSolidBrush(PdfRGBColor(Color.get_Black())) page.Canvas.DrawString("Hello, World!", font, brush, 10.0, 10.0) doc.SaveToFile("output.pdf") doc.Close() ``` -------------------------------- ### PdfBookmark.Text Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/api-reference/Bookmarks_Attachments.md Gets or sets the display text for a bookmark. ```APIDOC ## Bookmark Text ### Description Gets or sets the display text of the bookmark. ### Method `PdfBookmark.Text` ### Properties - **Text** (str) - The display text of the bookmark. ### Example ```python bookmark.Text = "Chapter 1: Introduction" ``` ``` -------------------------------- ### Create PDF Portfolio with Subfolders Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/Examples/pdf_python.md Demonstrates how to create a PDF portfolio by adding files and organizing them into subfolders. This is useful for bundling multiple documents within a single PDF. ```python # Create PDF document doc = PdfDocument() # Loop through files and add them to the portfolio i = 0 while i < num_files: # Add file to the collection doc.Collection.Folders.AddFile(file_path) # Create subfolder and add file to it folder = doc.Collection.Folders.CreateSubfolder("SubFolder" + str(i + 1)) folder.AddFile(file_path) i += 1 ``` -------------------------------- ### PdfBookmarkCollection.Count Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/api-reference/Bookmarks_Attachments.md Gets the number of root-level bookmarks in the document. ```APIDOC ## Get Bookmark Count ### Description Gets the number of root-level bookmarks. ### Method `PdfDocument.Bookmarks.Count` ### Properties - **Count** (int) - Number of root-level bookmarks. ### Example ```python for i in range(doc.Bookmarks.Count): bookmark = doc.Bookmarks[i] ``` ``` -------------------------------- ### Complete Color and Brush Example in Python Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/api-reference/Colors_Brushes_Pens.md Demonstrates the creation and usage of various color, brush, and pen types, including solid, custom RGB, gradient brushes, and predefined pens for drawing shapes on a PDF canvas. ```python from spire.pdf import * from spire.pdf.common import * doc = PdfDocument() page = doc.Pages.Add() canvas = page.Canvas # Solid colors red_brush = PdfSolidBrush(PdfRGBColor(Color.get_Red())) blue_pen = PdfPen(PdfRGBColor(Color.get_Blue()), 2.0) # Custom RGB color custom_color = PdfRGBColor(Color.FromArgb(200, 100, 50)) custom_brush = PdfSolidBrush(custom_color) # Gradient brush gradient = PdfLinearGradientBrush( PointF(10.0, 10.0), PointF(110.0, 110.0), PdfRGBColor(Color.get_White()), PdfRGBColor(Color.get_Black()) ) # Draw shapes canvas.DrawRectangle(red_brush, 10.0, 10.0, 100.0, 100.0) canvas.DrawEllipse(blue_pen, 10.0, 120.0, 100.0, 100.0) canvas.DrawRectangle(gradient, 120.0, 10.0, 100.0, 100.0) # Predefined helpers canvas.DrawLine(PdfPens.get_Green(), 10.0, 230.0, 220.0, 230.0) doc.SaveToFile("colors.pdf") doc.Close() ``` -------------------------------- ### Italic Property Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/api-reference/PdfFont.md Gets whether the font is italic. ```APIDOC ## Italic Property ### Description Gets whether the font is italic. ### Type `bool` ``` -------------------------------- ### Create PDF with Bookmarks and Attachments Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/api-reference/Bookmarks_Attachments.md This snippet shows how to load an existing PDF, add main and child bookmarks, embed multiple file attachments, set descriptions for attachments, and save the resulting comprehensive PDF. ```python from spire.pdf import * from spire.pdf.common import * doc = PdfDocument() doc.LoadFromFile("base.pdf") # Add bookmarks ch1_dest = PdfDestination(doc.Pages[0]) ch1 = doc.Bookmarks.Add("Part 1: Overview", ch1_dest) ch2_dest = PdfDestination(doc.Pages[5]) ch2 = doc.Bookmarks.Add("Part 2: Details", ch2_dest) # Add child bookmarks children = ch1.GetChildBookmarks() section_dest = PdfDestination(doc.Pages[1]) children.Add("Background", section_dest) # Add attachments (supporting files) doc.Attachments.Add("supporting_data.xlsx") doc.Attachments.Add("methodology.docx") doc.Attachments.Add("references.txt") # Set descriptions for i in range(doc.Attachments.Count): att = doc.Attachments[i] att.Description = f"Supporting material {i + 1}" doc.SaveToFile("comprehensive_document.pdf") doc.Close() ``` -------------------------------- ### Bold Property Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/api-reference/PdfFont.md Gets whether the font is bold. ```APIDOC ## Bold Property ### Description Gets whether the font is bold. ### Type `bool` ``` -------------------------------- ### Create a Simple PDF Document with Hello World Text Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/Examples/pdf_python.md This snippet demonstrates how to create a new PDF document and add a simple 'Hello, World!' text to its first page. ```python #Create a pdf document doc= PdfDocument() #Create one page page = doc.Pages.Add() s = "Hello, World" x = 10.0 y = 10.0 font = PdfFont(PdfFontFamily.Helvetica ,30.0) color = PdfRGBColor(Color.get_Black()) textBrush = PdfSolidBrush(color) #Draw the text page.Canvas.DrawString(s, font, textBrush, x, y) ``` -------------------------------- ### Create PDF Links and Annotations Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/Examples/pdf_python.md Demonstrates creating simple text links, web links using PdfTextWebLink, URI annotations, and JavaScript action annotations. ```python # Font setup font = PdfTrueTypeFont("Lucida Sans Unicode", 14.0, PdfFontStyle.Regular, True) font1 = PdfTrueTypeFont("Lucida Sans Unicode", 14.0, PdfFontStyle.Underline, True) format = PdfStringFormat() format.MeasureTrailingSpaces = True # Simple text link url1 = "http://www.e-iceblue.com" page.Canvas.DrawString("Simple Text Link: ", font, PdfBrushes.get_Orange(), 0.0, y, format) x = font.MeasureString("Simple Text Link: ", format).Width page.Canvas.DrawString(url1, font1, PdfBrushes.get_CadetBlue(), x, y) # Web link using PdfTextWebLink webLink = PdfTextWebLink() webLink.Text = "E-iceblue home" webLink.Url = url1 webLink.Font = font1 webLink.Brush = PdfBrushes.get_CadetBlue() webLink.DrawTextWebLink(page.Canvas, PointF(x, y)) # URI annotation text = "Google" location = PointF(x, y) size = font1.MeasureString(text) linkBounds = RectangleF(location, size) uriAnnotation = PdfUriAnnotation(linkBounds) uriAnnotation.Border = PdfAnnotationBorder(0.0) uriAnnotation.Uri = "http://www.google.com" newPage.Annotations.Add(uriAnnotation) page.Canvas.DrawString(text, font1, PdfBrushes.get_CadetBlue(), x, y) # URI annotation with JavaScript action text = "JavaScript Action (Click Me)" location = PointF(x-2, y-2) size = font1.MeasureString(text) size = SizeF(size.Width+5, size.Height+5) linkBounds = RectangleF(location, size) jsAnnotation = PdfUriAnnotation(linkBounds) jsAnnotation.Border = PdfAnnotationBorder(0.75) jsAnnotation.Color = PdfRGBColor(Color.get_CadetBlue()) script = "app.alert({cMsg: \"Hello.\", nIcon: 3, cTitle: \"JavaScript Action\"});" action = PdfJavaScriptAction(script) jsAnnotation.Action = action newPage.Annotations.Add(jsAnnotation) page.Canvas.DrawString(text, font1, PdfBrushes.get_CadetBlue(), x, y) # Forum and email links using PdfTextWebLink forumLink = PdfTextWebLink() forumLink.Text = "Go to forum to ask questions" forumLink.Url = "https://www.e-iceblue.com/forum/components-f5.html" forumLink.Font = font1 forumLink.Brush = PdfBrushes.get_CadetBlue() forumLink.DrawTextWebLink(page.Canvas, PointF(x, y)) emailLink = PdfTextWebLink() emailLink.Text = "Send an email" emailLink.Url = "mailto:support@e-iceblue.com" emailLink.Font = font1 emailLink.Brush = PdfBrushes.get_CadetBlue() emailLink.DrawTextWebLink(page.Canvas, PointF(x, y)) ``` -------------------------------- ### Size Property Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/api-reference/PdfFont.md Gets the font size in points. ```APIDOC ## Size Property ### Description The font size in points. ### Type `float` ### Example ```python font = PdfFont(PdfFontFamily.Helvetica, 12.0) print(font.Size) # Output: 12.0 ``` ``` -------------------------------- ### Create a Simple PDF Grid Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/Examples/pdf_python.md This example shows how to create a basic grid structure within a PDF document. It covers setting column widths, row heights, and populating cells with values and alignment. ```python # Create a pdf document doc = PdfDocument() # Add a new page page = doc.Pages.Add() # Create a grid grid = PdfGrid() grid.Columns.Add(5) # Iterate each column of grid for j in range(grid.Columns.Count): # Set width of column grid.Columns[j].Width = 100 # Add rows for i in range(10): grid.Rows.Add() # Set font styles for specific rows and cells trueTypeFont = PdfTrueTypeFont("Arial", 10.0, PdfFontStyle.Regular, True) height = 21.0 # Iterate each row of grid for i in range(grid.Rows.Count): gridRow = grid.Rows.get_Item(i) # Set the height for row gridRow.Height = height gridRow.Style.Font = trueTypeFont for j in range(gridRow.Cells.Count): gridRow.Cells.get_Item(j).Value = "Row_" + str(i+1) + "Cell_" + str(j+1) gridRow.Cells.get_Item(j).StringFormat = PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle) # Draw the updated grid on the page at a different location grid.Draw(page, PointF(10.0, 100.0)) ``` -------------------------------- ### ClientSize Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/api-reference/PdfCanvas.md Gets the dimensions (width and height) of the PDF canvas. ```APIDOC ## ClientSize ### Description The dimensions (width, height) of the canvas. ### Type SizeF ### Request Example ```python width = canvas.ClientSize.Width height = canvas.ClientSize.Height ``` ``` -------------------------------- ### Basic PDF Document Initialization Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/configuration.md Creates a new empty PDF document. No parameters are required for basic initialization. ```python doc = PdfDocument() ``` -------------------------------- ### PdfAttachment.Data Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/api-reference/Bookmarks_Attachments.md Gets the file content of the attachment as bytes. This property is read-only. ```APIDOC ## PdfAttachment.Data ### Description Gets the file content of the attachment as bytes. This property is read-only. ### Property Type bytes ### Example ```python # Extract attachment data = attachment.Data # Save to file with open(f"extracted_{attachment.FileName}", "wb") as f: f.write(data) ``` ``` -------------------------------- ### Create a PDF Document with Sections and Pages Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/Examples/pdf_python.md Demonstrates how to create a new PDF document, set margins, define sections with page settings, and add multiple pages to a section. ```python # Create a pdf document doc = PdfDocument() doc.ViewerPreferences.PageLayout = PdfPageLayout.TwoColumnLeft # Set the margin unitCvtr = PdfUnitConvertor() margin = PdfMargins() margin.Top = unitCvtr.ConvertUnits( 2.54, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point) margin.Bottom = margin.Top margin.Left = unitCvtr.ConvertUnits( 3.17, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point) margin.Right = margin.Left SetDocumentTemplate(doc, PdfPageSize.A4(), margin) # Create one section section = doc.Sections.Add() section.PageSettings.Size = PdfPageSize.A4() section.PageSettings.Margins = PdfMargins(0.0) SetSectionTemplate(section, PdfPageSize.A4(), margin, "Section 1") # Create one page page = section.Pages.Add() # Draw page DrawPage(page) page = section.Pages.Add() DrawPage(page) page = section.Pages.Add() DrawPage(page) page = section.Pages.Add() DrawPage(page) page = section.Pages.Add() DrawPage(page) ``` -------------------------------- ### PdfAttachmentCollection.Count Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/api-reference/Bookmarks_Attachments.md Gets the total number of attachments present in the PDF document. ```APIDOC ## PdfAttachmentCollection.Count ### Description Gets the total number of attachments present in the PDF document. ### Property Type int ### Example ```python for i in range(doc.Attachments.Count): attachment = doc.Attachments[i] ``` ``` -------------------------------- ### Get Attachment File Name Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/api-reference/Bookmarks_Attachments.md Retrieves the name of the attached file. ```python name = attachment.FileName print(f"Attached file: {name}") ``` -------------------------------- ### Create Launch File Action in New Window Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/Examples/pdf_python.md Configures a launch action to open a specified file in a new window. This is useful for linking to external resources or documents that should be opened independently. ```python # Create launch action to open file in new window launchAction = PdfLaunchAction(file_path, PdfFilePathType.Relative) launchAction.IsNewWindow = True ``` -------------------------------- ### PdfBookmark.Color Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/api-reference/Bookmarks_Attachments.md Gets or sets the color of the bookmark text in the outline panel. ```APIDOC ## Bookmark Color ### Description Gets or sets the color of the bookmark text in the outline panel. ### Method `PdfBookmark.Color` ### Properties - **Color** (PdfRGBColor) - The color of the bookmark text. ### Example ```python from spire.pdf.common import * bookmark.Color = PdfRGBColor(Color.get_Blue()) ``` ``` -------------------------------- ### PdfAnnotationCollection.Count Property Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/api-reference/Annotations.md Gets the total number of annotations present on the page. ```APIDOC ## PdfAnnotationCollection.Count Property ### Description Gets the number of annotations on the page. ### Type `int` ``` -------------------------------- ### Count Property Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/api-reference/PdfPageCollection.md Gets the total number of pages currently in the document. ```APIDOC ## Count Property ### Description Gets the total number of pages in the document. ### Type `int` ### Example ```python num_pages = doc.Pages.Count ``` ``` -------------------------------- ### Create PDF with Different Transparency Blend Modes Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/Examples/pdf_python.md This example shows how to create a PDF document with images displayed using various transparency blend modes. It iterates through available blend modes and applies different transparency levels. ```python #Create a pdf document doc = PdfDocument() #Create one section section = doc.Sections.Add() #for mode in Enum.GetValues(type_of(PdfBlendMode)): for mode in PdfBlendMode.__members__: page = section.Pages.Add() pageWidth = page.Canvas.ClientSize.Width y = 0.0 #Title y = y + 15 brush = PdfSolidBrush(PdfRGBColor(Color.get_OrangeRed())) font = PdfTrueTypeFont("Arial", 16.0, PdfFontStyle.Bold,True) format = PdfStringFormat(PdfTextAlignment.Center) text = "Transparency Blend Mode: {0:s}".format(mode) page.Canvas.DrawString(text, font, brush, pageWidth / 2, y, format) size = font.MeasureString(text, format) y = y + size.Height + 25 page.Canvas.DrawImage(image, 0.0, y, imageWidth, imageHeight) page.Canvas.Save() d = (page.Canvas.ClientSize.Width - imageWidth) / 5 x = d y = y + d / 2+40 for i in range(0, 5): alpha = 1.0 / 6 * (5 - i) page.Canvas.SetTransparency(alpha, alpha, PdfBlendMode[mode]) page.Canvas.DrawImage(image, x, y, imageWidth, imageHeight) x = x + d y = y + d / 2+ 40 page.Canvas.Restore() ``` -------------------------------- ### Strikeout Property Source: https://github.com/eiceblue/spire.pdf-for-python/blob/main/_autodocs/api-reference/PdfFont.md Gets whether the font has strikeout style applied. ```APIDOC ## Strikeout Property ### Description Gets whether the font has strikeout style applied. ### Type `bool` ```