### Install borb via pip Source: https://github.com/borb-pdf/borb/blob/master/README.md Install the borb library using pip. To ensure the latest version, uninstall and then reinstall without cache. ```bash pip install borb ``` ```bash pip uninstall borb pip install --no-cache borb ``` -------------------------------- ### Working with Color Representations and Schemes Source: https://context7.com/borb-pdf/borb/llms.txt Shows how to create and manipulate colors using various classes like `RGBColor`, `HexColor`, `GrayscaleColor`, `X11Color`, and `PantoneColor`. Includes examples of color conversion and using `ColorScheme` for analogous colors. ```python from borb.pdf import ( RGBColor, HexColor, CMYKColor, HSVColor, GrayscaleColor, X11Color, PantoneColor, ColorScheme, Document, Page, SingleColumnLayout, Paragraph, PDF ) # Various color representations red_rgb = RGBColor(red=220, green=50, blue=47) blue_hex = HexColor("#2980B9") gray = GrayscaleColor(0.5) # 0.0 = black, 1.0 = white x11_green = X11Color.SEA_GREEN pantone = PantoneColor.CLASSIC_BLUE print(red_rgb.to_hex_str()) # #DC322F print(blue_hex.to_rgb_color()) # RGBColor(41, 128, 185) print(x11_green.lighter().to_hex_str()) # Analogous color scheme colors = ColorScheme.analogous(X11Color.CORAL) # List[Color] doc = Document() page = Page() doc.append_page(page) layout = SingleColumnLayout(page) layout.append_layout_element( Paragraph("Colored text", font_color=pantone, font_size=14) ) PDF.write(what=doc, where_to="colors.pdf") ``` -------------------------------- ### Get Current borb Version Source: https://context7.com/borb-pdf/borb/llms.txt Retrieves the currently installed borb package version and allows for version comparisons. Uses the `Version` class. ```python from borb.pdf import Version v = Version.get_current_version() print(repr(v)) # 3.0.7 print(v >= Version("3.0.0")) # True print(v < Version("4.0.0")) # True print(v == Version("3.0.7")) # True ``` -------------------------------- ### Create a PDF with 'Hello World' Source: https://github.com/borb-pdf/borb/blob/master/README.md Generate a simple PDF document with a 'Hello World!' paragraph. Requires importing Document, Page, PageLayout, Paragraph, and PDF from borb.pdf. ```python from pathlib import Path from borb.pdf import Document, Page, PageLayout, SingleColumnLayout, Paragraph, PDF # Create an empty Document d: Document = Document() # Create an empty Page p: Page = Page() d.append_page(p) # Create a PageLayout l: PageLayout = SingleColumnLayout(p) # Add a Paragraph l.append_layout_element(Paragraph('Hello World!')) # Write the PDF PDF.write(what=d, where_to="assets/output.pdf") ``` -------------------------------- ### Create and Sign a License Source: https://github.com/borb-pdf/borb/blob/master/borb/pdf/license/README.md Use this method to generate a new license file. Provide all necessary details and paths to private keys for signing. ```python License.create_license( company="Example Corp", license_path="example_license.json", max_date=datetime.datetime.now() + datetime.timedelta(days=365), max_version=Version("2.1.0"), min_date=datetime.datetime.now(), name="John Doe", private_key_path="/path/to/private_key.pem", ) ``` -------------------------------- ### Create a Fixed-Width Table with Formatting Source: https://context7.com/borb-pdf/borb/llms.txt Illustrates creating a `FixedColumnWidthTable` with headers and rows. Helper methods like `striped()` and `set_padding_on_all_cells()` are used for styling. ```python from borb.pdf import ( Document, Page, SingleColumnLayout, FixedColumnWidthTable, FlexibleColumnWidthTable, Table, Paragraph, X11Color, HexColor, PDF ) doc = Document() page = Page() doc.append_page(page) layout = SingleColumnLayout(page) # --- Fixed-width table with header row --- headers = ["Name", "Role", "Department"] rows = [ ["Alice", "Engineer", "R&D"], ["Bob", "Manager", "Sales"], ["Charlie", "Designer", "UX"], ] table = FixedColumnWidthTable(number_of_rows=4, number_of_columns=3) for h in headers: table.append_layout_element( Table.TableCell( Paragraph(h, font_color=X11Color.WHITE), background_color=HexColor("#2C3E50"), ) ) for row in rows: for cell_text in row: table.append_layout_element(Paragraph(cell_text)) table.striped(even_row_color=HexColor("#ECF0F1"), odd_row_color=None) table.set_padding_on_all_cells(padding_top=4, padding_bottom=4, padding_left=6, padding_right=6) layout.append_layout_element(table) PDF.write(what=doc, where_to="table.pdf") ``` -------------------------------- ### Document Management: Create, Navigate, Modify Source: https://context7.com/borb-pdf/borb/llms.txt Illustrates core Document operations including appending, inserting, and removing pages, as well as merging other documents. Supports PDF/A and PDF/UA conformance levels. ```python from borb.pdf import Document, Page, PDF, Conformance # PDF/A-3B compliant document doc = Document(conformance=Conformance.PDF_A_3B) p1, p2 = Page(), Page() doc.append_page(p1) doc.append_page(p2) print(doc.get_number_of_pages()) # 2 # insert a third page at index 1 p3 = Page() doc.insert_page(p3, index=1) print(doc.get_number_of_pages()) # 3 # remove the last page doc.pop_page(-1) print(doc.get_number_of_pages()) # 2 # retrieve a page by index retrieved: Page = doc.get_page(0) print(retrieved.get_size()) # (595, 842) # merge another document other_doc = PDF.read("other.pdf") doc.append_document(other_doc) PDF.write(what=doc, where_to="merged.pdf") ``` -------------------------------- ### Enforcing PDF/A and PDF/UA Conformance Source: https://context7.com/borb-pdf/borb/llms.txt Illustrates how to create PDF documents that comply with PDF/A and PDF/UA standards by passing a `Conformance` value to the `Document` constructor. This automatically includes necessary metadata and profiles. ```python from borb.pdf import Document, Page, SingleColumnLayout, Paragraph, Conformance, PDF # PDF/A-2B compliant document doc = Document( conformance=Conformance.PDF_A_2B, on_non_conformance_print_warning=True, on_non_conformance_throw_assert=False, ) page = Page() doc.append_page(page) layout = SingleColumnLayout(page) layout.append_layout_element( Paragraph("Archival-safe content (PDF/A-2B)") ) print(Conformance.PDF_A_2B.requires_xmp_metadata()) # True print(Conformance.PDF_A_2B.requires_icc_color_profile()) # True print(Conformance.PDF_UA_1.requires_tagged_pdf()) # True PDF.write(what=doc, where_to="archive.pdf") ``` -------------------------------- ### Create a Two-Column Layout with Paragraphs Source: https://context7.com/borb-pdf/borb/llms.txt Demonstrates using `TwoColumnLayout` to place paragraphs sequentially across columns. Use `next_column()` and `next_page()` to manually control flow. ```python from borb.pdf import ( Document, Page, SingleColumnLayout, TwoColumnLayout, Paragraph, HexColor, Standard14Fonts, PDF ) doc = Document() page = Page() doc.append_page(page) layout = TwoColumnLayout(page) for i in range(1, 7): layout.append_layout_element( Paragraph( f"Column paragraph {i}", font=Standard14Fonts.get("Helvetica-Bold"), font_color=HexColor("#4A90D9"), font_size=11, ) ) # Force move to the next column manually layout.next_column() # Force move to the next page manually layout.next_page() PDF.write(what=doc, where_to="two_col.pdf") ``` -------------------------------- ### Create Pre-built Shapes: Arrow and Hexagon Source: https://context7.com/borb-pdf/borb/llms.txt Demonstrates creating and appending pre-built shapes like an arrow and a hexagon to a PDF layout. Requires importing `LineArt` and `LayoutElement`. ```python from borb.pdf import HexColor, X11Color, LayoutElement, LineArt # ... (assuming 'layout' and 'doc' are initialized) # Pre-built shape: arrow pointing right arrow = LineArt.arrow_right( stroke_color=HexColor("#E74C3C"), fill_color=HexColor("#FADBD8"), line_width=2, size=(100, 40), ) layout.append_layout_element(arrow) # Regular polygon: hexagon hex_shape = LineArt.regular_n_gon( n=6, stroke_color=X11Color.DARK_BLUE, fill_color=X11Color.LIGHT_BLUE, size=(80, 80), horizontal_alignment=LayoutElement.HorizontalAlignment.MIDDLE, ) layout.append_layout_element(hex_shape) # ... (assuming PDF.write is called later) ``` -------------------------------- ### Create Text Layout Elements: Paragraphs and Headings Source: https://context7.com/borb-pdf/borb/llms.txt Shows how to use `Paragraph`, `Heading`, and `HeterogeneousParagraph` for text content. `Heading` supports table of contents entries, and `HeterogeneousParagraph` allows mixed styles within a single paragraph. ```python from borb.pdf import ( Document, Page, SingleColumnLayout, Paragraph, Heading, HeterogeneousParagraph, Chunk, LayoutElement, HexColor, X11Color, Standard14Fonts, PDF ) doc = Document() page = Page() doc.append_page(page) layout = SingleColumnLayout(page) # Heading (level 1) layout.append_layout_element( Heading("Introduction", level=1, font_size=18, font_color=X11Color.DARK_BLUE) ) # Plain paragraph layout.append_layout_element( Paragraph( "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", font_size=11, text_alignment=LayoutElement.TextAlignment.JUSTIFIED, font_color=X11Color.BLACK, ) ) # Mixed-style paragraph layout.append_layout_element( HeterogeneousParagraph( chunks=[ Chunk("Important: ", font=Standard14Fonts.get("Helvetica-Bold"), font_color=HexColor("#E74C3C")), Chunk("read this carefully.", font_size=11), ] ) ) PDF.write(what=doc, where_to="text.pdf") ``` -------------------------------- ### Register and Verify a License Source: https://github.com/borb-pdf/borb/blob/master/borb/pdf/license/README.md Call this function to register a license file. It performs verification checks and returns true if the license is valid. ```python if License.register("example_license.json"): print("License is valid and registered.") else: print("License verification failed.") ``` -------------------------------- ### Create 16:9 Slideshows with Slideshow Source: https://context7.com/borb-pdf/borb/llms.txt The Slideshow class utilizes a fluent builder pattern similar to A4Portrait but is optimized for 16:9 slides. Each append_* method initiates a new slide. ```python from borb.pdf import Slideshow ( Slideshow() .append_title_slide( title="Annual Review 2024", subtitle="Presented by the Strategy Team", ) .append_section_title("Financial Highlights") .append_barchart( xs=[4.2, 5.1, 6.8], ys=["Q1", "Q2", "Q3"], y_label="Revenue ($M)", ) .append_map_of_the_world(marked_countries=["United States", "Germany", "Japan"]) .append_blank() .save("annual_review.pdf") ) ``` -------------------------------- ### Page Creation with Custom Dimensions and Rotation Source: https://context7.com/borb-pdf/borb/llms.txt Demonstrates creating PDF pages with standard sizes (A4, Letter Landscape) and custom dimensions. Includes rotating pages clockwise. ```python from borb.pdf import Document, Page, PageSize, PDF, SingleColumnLayout, Paragraph doc = Document() # A4 portrait (default) a4 = Page() # 595 × 842 # US Letter landscape letter_ls = Page( width_in_points=PageSize.LETTER_LANDSCAPE[0], height_in_points=PageSize.LETTER_LANDSCAPE[1], ) # Custom 800 × 600 page custom = Page(width_in_points=800, height_in_points=600) custom.rotate_right() # rotate 90° clockwise for p in [a4, letter_ls, custom]: doc.append_page(p) # Use the A4 page l = SingleColumnLayout(a4) l.append_layout_element(Paragraph("A4 content")) print(a4.uses_text()) # True print(a4.uses_color_images()) # False PDF.write(what=doc, where_to="pages.pdf") ``` -------------------------------- ### Create Unordered, Ordered, Roman Numeral, and ABC Lists Source: https://context7.com/borb-pdf/borb/llms.txt Demonstrates how to create different types of lists, including nested lists, using `UnorderedList`, `OrderedList`, `RomanNumeralOrderedList`, and `ABCOrderedList`. Ensure `Paragraph` elements are appended to list items. ```python from borb.pdf import ( Document, Page, SingleColumnLayout, UnorderedList, OrderedList, RomanNumeralOrderedList, Paragraph, PDF ) doc = Document() page = Page() doc.append_page(page) layout = SingleColumnLayout(page) ul = UnorderedList() for item in ["Apples", "Bananas", "Cherries"]: ul.append_layout_element(Paragraph(item)) # Nested list sub = OrderedList() for item in ["Sub-item A", "Sub-item B"]: sub.append_layout_element(Paragraph(item, font_size=10)) ul.append_layout_element(sub) layout.append_layout_element(ul) rl = RomanNumeralOrderedList() for item in ["First", "Second", "Third"]: rl.append_layout_element(Paragraph(item)) layout.append_layout_element(rl) PDF.write(what=doc, where_to="lists.pdf") ``` -------------------------------- ### Write PDF to File or BytesIO Source: https://context7.com/borb-pdf/borb/llms.txt Demonstrates how to write a borb Document to a file path or an in-memory BytesIO buffer. Parent directories are created automatically, and existing files are overwritten. ```python import io from borb.pdf import Document, Page, SingleColumnLayout, Paragraph, PDF # --- create --- doc: Document = Document() page: Page = Page() # default A4 portrait: 595 × 842 pts doc.append_page(page) layout = SingleColumnLayout(page) layout.append_layout_element(Paragraph("Hello, borb!")) # --- write to file --- PDF.write(what=doc, where_to="output/hello.pdf") # --- write to BytesIO (e.g. for HTTP response) --- buffer = io.BytesIO() PDF.write(what=doc, where_to=buffer) pdf_bytes: bytes = buffer.getvalue() print(f"PDF size: {len(pdf_bytes)} bytes") # PDF size: 3142 bytes ``` -------------------------------- ### Embed Images from URL and Local File Source: https://context7.com/borb-pdf/borb/llms.txt Demonstrates embedding images using the `Image` element, supporting sources from URLs or local file paths. The `size` parameter controls dimensions, and `horizontal_alignment` can be set. ```python from pathlib import Path from borb.pdf import ( Document, Page, SingleColumnLayout, Image, LayoutElement, PDF ) doc = Document() page = Page() doc.append_page(page) layout = SingleColumnLayout(page) # From URL layout.append_layout_element( Image( "https://images.unsplash.com/photo-1506748686214-e9df14d4d9d0?w=400", size=(300, 186), horizontal_alignment=LayoutElement.HorizontalAlignment.MIDDLE, ) ) # From local file layout.append_layout_element( Image( Path("logo/borb_square_64_64.png"), size=(64, 64), border_color=None, ) ) PDF.write(what=doc, where_to="images.pdf") ``` -------------------------------- ### Read PDF from Disk Source: https://context7.com/borb-pdf/borb/llms.txt Shows how to read an existing PDF file into a borb Document object. Returns None if the file cannot be parsed. Useful for inspecting or modifying existing PDFs. ```python from borb.pdf import PDF, Document doc: Document = PDF.read("output/hello.pdf") assert doc is not None print(f"Pages: {doc.get_number_of_pages()}") # Pages: 1 print(f"Title: {doc.get_title()}") # Title: None print(f"Author: {doc.get_author()}") # Author: None print(f"Producer: {doc.get_producer()}") # Producer: borb ``` -------------------------------- ### Build A4 Reports with A4Portrait Source: https://context7.com/borb-pdf/borb/llms.txt Use A4Portrait for a fluent builder API to create A4 documents. It automatically handles page overflow and element sizing, allowing for chaining of content additions. ```python from borb.pdf import A4Portrait ( A4Portrait() .append_section_title("Q3 Sales Report") .append_single_column_of_text( "This report covers all sales activities for Q3 2024." ) .append_barchart( xs=[120_000, 95_000, 140_000], ys=["July", "August", "September"], y_label="Revenue (USD)", ) .append_table( tabular_data=[ ["Region", "Units", "Revenue"], ["North", "1 200", "$120 000"], ["South", "950", "$95 000"], ["West", "1 400", "$140 000"], ] ) .append_quote( author="Peter Drucker", quote="Efficiency is doing things right; effectiveness is doing the right things.", ) .append_qr_code(url="https://example.com/sales-dashboard") .save("q3_report.pdf") ) ``` -------------------------------- ### Extracting Data from PDFs using Pipeline Source: https://context7.com/borb-pdf/borb/llms.txt Demonstrates the use of `Pipeline` to extract text, images, and specific patterns from existing PDF documents. Various `Sink` objects like `GetText`, `GetImages`, and `GetRegularExpression` can be chained with `Source` and filters. ```python from borb.pdf import ( PDF, Pipeline, GetText, GetImages, GetColors, GetRegularExpression, Source, EvenPages, ByFontSize, ) from borb.pdf.toolkit.source.operator.source import Source doc = PDF.read("output/hello.pdf") assert doc is not None # --- Extract all text --- sink_text = GetText() Pipeline(pipes=[Source(), sink_text]).process(doc) text: str = sink_text.get_output() print(repr(text)) # 'Hello, borb!\n' # --- Extract text matching a regex --- sink_regex = GetRegularExpression(regular_expression=r"\d{4}-\d{2}-\d{2}") Pipeline(pipes=[Source(), sink_regex]).process(doc) matches = sink_regex.get_output() # List of matched strings # --- Extract images on even pages only --- sink_images = GetImages() Pipeline(pipes=[Source(), EvenPages(), sink_images]).process(doc) images = sink_images.get_output() # Dict[int, List[PIL.Image]] # --- Extract only large-font text --- sink_big = GetText() Pipeline(pipes=[Source(), ByFontSize(minimum_font_size=18), sink_big]).process(doc) big_text: str = sink_big.get_output() ``` -------------------------------- ### Embed Machine-Readable Codes with QRCode and Barcode Source: https://context7.com/borb-pdf/borb/llms.txt QRCode and Barcode are LayoutElement subclasses for rendering machine-readable codes. They require optional packages 'segno' for QR codes and 'python-barcode' for standard barcodes. ```python from borb.pdf import ( Document, Page, SingleColumnLayout, QRCode, Barcode, LayoutElement, PDF ) doc = Document() page = Page() doc.append_page(page) layout = SingleColumnLayout(page) layout.append_layout_element( QRCode( qr_code_data="https://borbpdf.com", size=(100, 100), horizontal_alignment=LayoutElement.HorizontalAlignment.MIDDLE, ) ) layout.append_layout_element( Barcode( data="978-3-16-148410-0", barcode_type=Barcode.BarcodeType.EAN_13, size=(200, 80), horizontal_alignment=LayoutElement.HorizontalAlignment.MIDDLE, ) ) PDF.write(what=doc, where_to="codes.pdf") ``` -------------------------------- ### Create Interactive PDF Form Elements Source: https://context7.com/borb-pdf/borb/llms.txt Demonstrates how to add interactive form elements such as text boxes, checkboxes, drop-down lists, and radio buttons to a PDF page. Values can be pre-filled. ```python from borb.pdf import ( Document, Page, SingleColumnLayout, Paragraph, TextBox, CheckBox, DropDownList, RadioButton, PDF ) doc = Document() page = Page() doc.append_page(page) layout = SingleColumnLayout(page) layout.append_layout_element(Paragraph("Name:")) layout.append_layout_element(TextBox(field_name="name", value="John Doe")) layout.append_layout_element(Paragraph("Subscribe to newsletter:")) layout.append_layout_element(CheckBox(field_name="newsletter", value=True)) layout.append_layout_element(Paragraph("Country:")) layout.append_layout_element( DropDownList( field_name="country", choices=["USA", "UK", "Germany", "France"], value="USA", ) ) layout.append_layout_element(Paragraph("Gender:")) for gender in ["Male", "Female", "Non-binary"]: layout.append_layout_element( RadioButton(field_name="gender", value=gender) ) layout.append_layout_element(Paragraph(gender, font_size=10)) PDF.write(what=doc, where_to="form.pdf") ``` -------------------------------- ### Create Vector Graphics with LineArt and Shape Source: https://context7.com/borb-pdf/borb/llms.txt LineArt offers factory methods for common geometric primitives, while Shape allows rendering arbitrary point lists as filled or stroked paths. These are fundamental for creating custom vector graphics. ```python from borb.pdf import ( Document, Page, SingleColumnLayout, LineArt, Shape, HexColor, X11Color, LayoutElement, PDF ) doc = Document() page = Page() doc.append_page(page) layout = SingleColumnLayout(page) ``` -------------------------------- ### Add Interactive Annotations to a PDF Page Source: https://context7.com/borb-pdf/borb/llms.txt Shows how to add various interactive annotations, including hyperlinks, highlight annotations, and rubber stamp annotations, to a PDF page. Requires importing `LinkAnnotation`, `HighlightAnnotation`, and `RubberStampAnnotation`. ```python from borb.pdf import ( Document, Page, SingleColumnLayout, Paragraph, LinkAnnotation, HighlightAnnotation, RubberStampAnnotation, X11Color, PDF ) doc = Document() page = Page() doc.append_page(page) layout = SingleColumnLayout(page) layout.append_layout_element(Paragraph("Visit our website for more information.")) # Hyperlink annotation layout.append_layout_element( LinkAnnotation( uri="https://borbpdf.com", bounding_box=(50, 700, 200, 720), ) ) # Highlight annotation layout.append_layout_element( HighlightAnnotation( bounding_box=(50, 680, 300, 700), color=X11Color.YELLOW, ) ) # Rubber stamp layout.append_layout_element( RubberStampAnnotation( rubber_stamp_annotation_name=RubberStampAnnotation.RubberStampAnnotationName.APPROVED, bounding_box=(400, 700, 550, 740), ) ) PDF.write(what=doc, where_to="annotations.pdf") ``` -------------------------------- ### Re-enable borb Usage Statistics Source: https://github.com/borb-pdf/borb/blob/master/PRIVACY_POLICY.md Call this method to resume sending telemetry events. This is useful if you previously opted out and wish to contribute usage data again. ```python UsageStatistics.opt_in() ``` -------------------------------- ### Git Commit Message Format Source: https://github.com/borb-pdf/borb/blob/master/CONTRIBUTING.md Follow this format for all Git commit messages to ensure clarity and consistency in the project history. The subject line should be concise and imperative, the body should explain the 'what' and 'why', and the footer should include issue references. ```git