add auto generate .svg python scripts

This commit is contained in:
gab-k committed 2024-11-25 20:52:21 +01:00
1 parent dc53d98fda
commit 201d521be8
9 files changed
+447288 -40742

No files matched your search

+85
View File
@@ -0,0 +1,85 @@
##############################
# #
# #
# -----p2 #
# | | #
# | | <- Crop Window # <- Whole PDF Window
# | | #
# p1----| #
# #
##############################
# Coordinate origin is at bottom left of PDF window
#
# y
# î
# |
# |
# +-----> x
import argparse
from PyPDF2 import PdfReader, PdfWriter
def crop_pdf(input_path, output_path, p1, p2):
"""
Crop a PDF file based on the given bottom-left (p1) and top-right (p2) coordinates.
Parameters:
- input_path (str): Path to the input PDF file.
- output_path (str): Path to save the cropped PDF file.
- p1 (tuple): Bottom-left corner of the crop window (x, y).
- p2 (tuple): Top-right corner of the crop window (x, y).
"""
# Validate coordinates
if p1[0] >= p2[0]:
raise ValueError("Invalid x dimensions: p1[0] must be less than p2[0]")
if p1[1] >= p2[1]:
raise ValueError("Invalid y dimensions: p1[1] must be less than p2[1]")
# Open the input PDF
with open(input_path, "rb") as in_f:
input_pdf = PdfReader(in_f)
output_pdf = PdfWriter()
num_pages = len(input_pdf.pages)
print(f"Document has {num_pages} pages.")
# Loop through all pages
for i in range(num_pages):
page = input_pdf.pages[i]
# Set the cropbox properties for the page
page.cropbox.lower_left = p1 # Bottom-left corner
page.cropbox.upper_right = p2 # Top-right corner
# Debug information about the crop box
print(f"Page {i + 1}:")
print(f" - Cropbox Lower Left: {page.cropbox.lower_left}")
print(f" - Cropbox Upper Right: {page.cropbox.upper_right}")
# Add the modified page to the writer
output_pdf.add_page(page)
# Write the final output
with open(output_path, "wb") as out_f:
output_pdf.write(out_f)
print(f"Cropped PDF saved as {output_path}")
# Add argument parsing to handle command-line inputs
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Crop a PDF file based on coordinates.")
parser.add_argument("input_path", type=str, help="Path to the input PDF file.")
parser.add_argument("output_path", type=str, help="Path to save the cropped PDF file.")
parser.add_argument("p1", type=float, nargs=2, help="Bottom-left corner of the crop window (x, y).")
parser.add_argument("p2", type=float, nargs=2, help="Top-right corner of the crop window (x, y).")
args = parser.parse_args()
# Convert command-line inputs for coordinates
bottom_left = tuple(args.p1)
top_right = tuple(args.p2)
# Call the crop function
try:
crop_pdf(args.input_path, args.output_path, bottom_left, top_right)
except ValueError as e:
print(f"Error: {e}")
+134
View File
@@ -0,0 +1,134 @@
"""
Script for automatically generating .svg files for documentation
How to use:
1. Install Inkscape and add to PATH
2. Install KiCad and add to PATH
3. Install PyPDF2
4. Copy the schematic_theme.json file into the following directory:
Linux: ~.config/kicad/<version>/colors
Windows: %appdata%/kicad/<version>/colors
"""
import subprocess
import os
# Output directory path
svg_dir = "../docs/svg/"
# Temp directory path
temp_dir = "temp/"
# .kicad_sch path/filename
kicad_sch_filename = "../KiCad/RP2040-Decoder.kicad_sch"
# Define crop areas with p1 (bottom-left) and p2 (top-right) points and custom pdf_name
crop_areas = {
"Input Stage": {
"p1": (60, 440), # Bottom-left corner (x1, y1)
"p2": (430, 560), # Top-right corner (x2, y2)
"name": "Input_Stage"
},
"Motor Driver": {
"p1": (600, 125),
"p2": (810, 315),
"name": "Motor_Driver"
},
"Auxillary Outputs": {
"p1": (620, 395),
"p2": (810, 555),
"name": "Aux_Outputs"
}
}
# 1. Create temp directory
try:
os.mkdir(temp_dir)
print(f"Directory '{temp_dir}' created successfully.")
except FileExistsError:
print(f"Directory '{temp_dir}' already exists.")
except PermissionError:
print(f"Permission denied: Unable to create '{temp_dir}'.")
except Exception as e:
print(f"An error occurred: {e}")
# 2. Export from KiCad with and without drawing sheet
subprocess.run(
["kicad-cli", "sch", "export", "pdf", "--no-background-color", "--exclude-drawing-sheet", "--theme", "schematic_theme",
"--output", temp_dir + "RP2040-Decoder_temp.pdf", kicad_sch_filename],
check=True
)
subprocess.run(
["kicad-cli", "sch", "export", "svg", "--no-background-color", "--theme", "schematic_theme",
"--output", svg_dir, kicad_sch_filename],
check=True
)
# 3. Crop the PDF for each specified crop area
for crop_key, crop_data in crop_areas.items():
p1 = crop_data["p1"] # (x1, y1)
p2 = crop_data["p2"] # (x2, y2)
pdf_path = temp_dir + crop_data["name"] + ".pdf" # Name of the output cropped PDF
subprocess.run(
["python", "crop_pdf.py", temp_dir + "RP2040-Decoder_temp.pdf", pdf_path, str(p1[0]), str(p1[1]), str(p2[0]), str(p2[1])],
check=True
)
print(f"Cropped part {crop_key} saved as {pdf_path}")
# 4. Convert each cropped PDF to SVG using Inkscape
for crop_key, crop_data in crop_areas.items():
svg_path = svg_dir + crop_data["name"] + ".svg"
pdf_path = temp_dir + crop_data["name"] + ".pdf"
subprocess.run(
["inkscape", "--export-type=svg", "--export-filename=" + svg_path, pdf_path],
check=True
)
print(f"Converted {pdf_path} to {svg_path}")
# 5. Set transparency for each SVG
for crop_key, crop_data in crop_areas.items():
svg_path = svg_dir + crop_data["name"] + ".svg"
subprocess.run(
["python", "set_opacity.py", svg_path, svg_path],
check=True
)
print(f"Set transparency for {svg_path}")
# 6. Clean up the temporary PDF files and attempt to delete temp directory
for crop_key, crop_data in crop_areas.items():
pdf_path = temp_dir + crop_data["name"] + ".pdf"
try:
os.remove(pdf_path) # Attempt to delete the cropped PDF
print(f"Deleted temporary file: {pdf_path}")
except FileNotFoundError:
print(f"File not found: {pdf_path}")
except PermissionError:
print(f"Permission denied: Unable to delete '{pdf_path}'.")
except Exception as e:
print(f"An error occurred while deleting '{pdf_path}': {e}")
temp_file = temp_dir + "RP2040-Decoder_temp.pdf"
try:
os.remove(temp_file) # Attempt to delete the final temporary file
print(f"Deleted temporary file: {temp_file}")
except FileNotFoundError:
print(f"File not found: {temp_file}")
except PermissionError:
print(f"Permission denied: Unable to delete '{temp_file}'.")
except Exception as e:
print(f"An error occurred while deleting '{temp_file}': {e}")
try:
os.rmdir(temp_dir)
print(f"Directory '{temp_dir}' deleted successfully.")
except FileNotFoundError:
print(f"Directory '{temp_dir}' does not exist.")
except OSError:
print(f"Directory '{temp_dir}' is not empty or cannot be removed.")
except PermissionError:
print(f"Permission denied: Unable to delete '{temp_dir}'.")
except Exception as e:
print(f"An error occurred: {e}")
+220
View File
@@ -0,0 +1,220 @@
{
"3d_viewer": {
"background_bottom": "rgb(102, 102, 128)",
"background_top": "rgb(204, 204, 230)",
"board": "rgba(51, 43, 23, 0.902)",
"copper": "rgb(179, 156, 0)",
"silkscreen_bottom": "rgb(230, 230, 230)",
"silkscreen_top": "rgb(230, 230, 230)",
"soldermask_bottom": "rgba(20, 51, 36, 0.831)",
"soldermask_top": "rgba(20, 51, 36, 0.831)",
"solderpaste": "rgb(128, 128, 128)"
},
"board": {
"anchor": "rgb(255, 38, 226)",
"aux_items": "rgb(255, 255, 255)",
"b_adhes": "rgb(0, 0, 132)",
"b_crtyd": "rgb(38, 233, 255)",
"b_fab": "rgb(88, 93, 132)",
"b_mask": "rgba(2, 255, 238, 0.400)",
"b_paste": "rgba(0, 194, 194, 0.902)",
"b_silks": "rgb(232, 178, 167)",
"background": "rgb(0, 16, 35)",
"cmts_user": "rgb(89, 148, 220)",
"conflicts_shadow": "rgba(255, 0, 5, 0.502)",
"copper": {
"b": "rgb(77, 127, 196)",
"f": "rgb(200, 52, 52)",
"in1": "rgb(127, 200, 127)",
"in10": "rgb(237, 124, 51)",
"in11": "rgb(91, 195, 235)",
"in12": "rgb(247, 111, 142)",
"in13": "rgb(167, 165, 198)",
"in14": "rgb(40, 204, 217)",
"in15": "rgb(232, 178, 167)",
"in16": "rgb(242, 237, 161)",
"in17": "rgb(237, 124, 51)",
"in18": "rgb(91, 195, 235)",
"in19": "rgb(247, 111, 142)",
"in2": "rgb(206, 125, 44)",
"in20": "rgb(167, 165, 198)",
"in21": "rgb(40, 204, 217)",
"in22": "rgb(232, 178, 167)",
"in23": "rgb(242, 237, 161)",
"in24": "rgb(237, 124, 51)",
"in25": "rgb(91, 195, 235)",
"in26": "rgb(247, 111, 142)",
"in27": "rgb(167, 165, 198)",
"in28": "rgb(40, 204, 217)",
"in29": "rgb(232, 178, 167)",
"in3": "rgb(79, 203, 203)",
"in30": "rgb(242, 237, 161)",
"in4": "rgb(219, 98, 139)",
"in5": "rgb(167, 165, 198)",
"in6": "rgb(40, 204, 217)",
"in7": "rgb(232, 178, 167)",
"in8": "rgb(242, 237, 161)",
"in9": "rgb(141, 203, 129)"
},
"cursor": "rgb(255, 255, 255)",
"drc_error": "rgba(215, 91, 107, 0.800)",
"drc_exclusion": "rgba(255, 255, 255, 0.800)",
"drc_warning": "rgba(255, 208, 66, 0.800)",
"dwgs_user": "rgb(194, 194, 194)",
"eco1_user": "rgb(180, 219, 210)",
"eco2_user": "rgb(216, 200, 82)",
"edge_cuts": "rgb(208, 210, 205)",
"f_adhes": "rgb(132, 0, 132)",
"f_crtyd": "rgb(255, 38, 226)",
"f_fab": "rgb(175, 175, 175)",
"f_mask": "rgba(216, 100, 255, 0.400)",
"f_paste": "rgba(180, 160, 154, 0.902)",
"f_silks": "rgb(242, 237, 161)",
"footprint_text_invisible": "rgb(132, 132, 132)",
"grid": "rgb(132, 132, 132)",
"grid_axes": "rgb(194, 194, 194)",
"locked_shadow": "rgba(255, 38, 226, 0.502)",
"margin": "rgb(255, 38, 226)",
"pad_plated_hole": "rgb(194, 194, 0)",
"pad_through_hole": "rgb(227, 183, 46)",
"page_limits": "rgb(132, 132, 132)",
"plated_hole": "rgb(26, 196, 210)",
"ratsnest": "rgba(0, 248, 255, 0.349)",
"user_1": "rgb(194, 194, 194)",
"user_2": "rgb(89, 148, 220)",
"user_3": "rgb(180, 219, 210)",
"user_4": "rgb(216, 200, 82)",
"user_5": "rgb(194, 194, 194)",
"user_6": "rgb(89, 148, 220)",
"user_7": "rgb(180, 219, 210)",
"user_8": "rgb(216, 200, 82)",
"user_9": "rgb(232, 178, 167)",
"via_blind_buried": "rgb(187, 151, 38)",
"via_hole": "rgb(227, 183, 46)",
"via_micro": "rgb(0, 132, 132)",
"via_through": "rgb(236, 236, 236)",
"worksheet": "rgb(200, 114, 171)"
},
"gerbview": {
"axes": "rgb(0, 0, 132)",
"background": "rgb(0, 0, 0)",
"dcodes": "rgb(255, 255, 255)",
"grid": "rgb(132, 132, 132)",
"layers": [
"rgb(200, 52, 52)",
"rgb(127, 200, 127)",
"rgb(206, 125, 44)",
"rgb(79, 203, 203)",
"rgb(219, 98, 139)",
"rgb(167, 165, 198)",
"rgb(40, 204, 217)",
"rgb(232, 178, 167)",
"rgb(242, 237, 161)",
"rgb(141, 203, 129)",
"rgb(237, 124, 51)",
"rgb(91, 195, 235)",
"rgb(247, 111, 142)",
"rgb(77, 127, 196)",
"rgb(200, 52, 52)",
"rgb(127, 200, 127)",
"rgb(206, 125, 44)",
"rgb(79, 203, 203)",
"rgb(219, 98, 139)",
"rgb(167, 165, 198)",
"rgb(40, 204, 217)",
"rgb(232, 178, 167)",
"rgb(242, 237, 161)",
"rgb(141, 203, 129)",
"rgb(237, 124, 51)",
"rgb(91, 195, 235)",
"rgb(247, 111, 142)",
"rgb(77, 127, 196)",
"rgb(200, 52, 52)",
"rgb(127, 200, 127)",
"rgb(206, 125, 44)",
"rgb(79, 203, 203)",
"rgb(219, 98, 139)",
"rgb(167, 165, 198)",
"rgb(40, 204, 217)",
"rgb(232, 178, 167)",
"rgb(242, 237, 161)",
"rgb(141, 203, 129)",
"rgb(237, 124, 51)",
"rgb(91, 195, 235)",
"rgb(247, 111, 142)",
"rgb(77, 127, 196)",
"rgb(200, 52, 52)",
"rgb(127, 200, 127)",
"rgb(206, 125, 44)",
"rgb(79, 203, 203)",
"rgb(219, 98, 139)",
"rgb(167, 165, 198)",
"rgb(40, 204, 217)",
"rgb(232, 178, 167)",
"rgb(242, 237, 161)",
"rgb(141, 203, 129)",
"rgb(237, 124, 51)",
"rgb(91, 195, 235)",
"rgb(247, 111, 142)",
"rgb(77, 127, 196)",
"rgb(200, 52, 52)",
"rgb(127, 200, 127)",
"rgb(206, 125, 44)",
"rgb(79, 203, 203)"
],
"negative_objects": "rgb(132, 132, 132)",
"page_limits": "rgb(132, 132, 132)",
"worksheet": "rgb(0, 0, 132)"
},
"meta": {
"name": "schematic_theme",
"version": 5
},
"schematic": {
"anchor": "rgb(0, 0, 255)",
"aux_items": "rgb(0, 0, 0)",
"background": "rgb(245, 244, 239)",
"brightened": "rgb(255, 0, 255)",
"bus": "rgb(0, 0, 132)",
"bus_junction": "rgb(0, 0, 132)",
"component_body": "rgb(255, 255, 194)",
"component_outline": "rgb(132, 0, 0)",
"cursor": "rgb(15, 15, 15)",
"dnp_marker": "rgba(220, 9, 13, 0.702)",
"erc_error": "rgba(230, 9, 13, 0.800)",
"erc_exclusion": "rgba(94, 194, 194, 0.800)",
"erc_warning": "rgba(209, 146, 0, 0.800)",
"fields": "rgb(132, 0, 132)",
"grid": "rgb(181, 181, 181)",
"grid_axes": "rgb(0, 0, 132)",
"hidden": "rgb(94, 194, 194)",
"hovered": "rgb(0, 0, 255)",
"junction": "rgb(0, 150, 0)",
"label_global": "rgb(132, 0, 0)",
"label_hier": "rgb(114, 86, 0)",
"label_local": "rgb(0, 107, 255)",
"netclass_flag": "rgb(72, 72, 72)",
"no_connect": "rgb(0, 0, 132)",
"note": "rgb(205, 0, 21)",
"note_background": "rgba(0, 0, 0, 0.000)",
"op_currents": "rgb(224, 0, 12)",
"op_voltages": "rgb(132, 0, 50)",
"override_item_colors": false,
"page_limits": "rgb(181, 181, 181)",
"pin": "rgb(132, 0, 0)",
"pin_name": "rgb(0, 100, 100)",
"pin_number": "rgb(169, 0, 0)",
"private_note": "rgb(72, 72, 255)",
"reference": "rgb(0, 100, 100)",
"shadow": "rgba(102, 179, 255, 0.800)",
"sheet": "rgb(132, 0, 0)",
"sheet_background": "rgba(255, 255, 255, 0.000)",
"sheet_fields": "rgb(132, 0, 132)",
"sheet_filename": "rgb(114, 86, 0)",
"sheet_label": "rgb(0, 100, 100)",
"sheet_name": "rgb(0, 100, 100)",
"value": "rgb(0, 100, 100)",
"wire": "rgb(0, 150, 0)",
"worksheet": "rgb(132, 0, 0)"
}
}
+46
View File
@@ -0,0 +1,46 @@
import re
import argparse
def set_opacity(input_file, output_file):
"""
Replace all occurrences of 'fill-opacity:1' with 'fill-opacity:0',
except when preceded by 'fill:#ffffc2'.
:param input_file: Path to the input SVG file.
:param output_file: Path to save the modified SVG file.
"""
try:
# Read the content of the input SVG file
with open(input_file, 'r') as file:
svg_content = file.read()
# Regex to match 'fill-opacity:1' and not preceded by 'fill:#ffffc2'
pattern = r'(?<!fill:#ffffc2;)fill-opacity:1'
modified_content = re.sub(pattern, 'fill-opacity:0', svg_content)
# Save the modified content to the output file
with open(output_file, 'w') as file:
file.write(modified_content)
print(f"Modified SVG saved as: {output_file}")
except Exception as e:
print(f"An error occurred: {e}")
def main():
# Set up the argument parser
parser = argparse.ArgumentParser(
description="Modify SVG files by replacing 'fill-opacity:1' with 'fill-opacity:0', "
"except when preceded by 'fill:#ffffc2'."
)
parser.add_argument('input_file', type=str, help="Path to the input SVG file.")
parser.add_argument('output_file', type=str, help="Path to save the modified SVG file.")
# Parse the arguments
args = parser.parse_args()
# Call the function with the provided file paths
set_opacity(args.input_file, args.output_file)
if __name__ == "__main__":
main()