dxfedit/01_Aspose_CAD_Python/print_cad_to_pdf.py
puzzlesion fc79d59e53 feat(python): add scripts for CAD to PDF conversion and block finding
This commit introduces two new feature scripts to the Aspose_CAD_Python project:

- print_cad_to_pdf.py: A script to export CAD drawings to PDF format, providing a direct way to generate printable documents.

- step1_find_block_coordinates.py: A utility to find and list the coordinates of specific blocks within a CAD file, which is a crucial first step for automated plotting and data extraction.

Additionally, relevant documentation in .specstory has been added to reflect these new capabilities.
2025-09-12 17:20:36 +08:00

95 lines
3.5 KiB
Python

import aspose.cad as cad
import os
import argparse
def find_shx_files(fonts_dir):
"""Finds all .shx files in a directory."""
shx_files = []
for root, _, files in os.walk(fonts_dir):
for file in files:
if file.lower().endswith('.shx'):
shx_files.append(os.path.join(root, file))
return shx_files
def print_cad_to_pdf(input_dwg, output_pdf, fonts_dir):
"""
Converts a CAD drawing (DWG) to a PDF file, using specified custom fonts.
:param input_dwg: Path to the input DWG file.
:param output_pdf: Path to save the output PDF file.
:param fonts_dir: Directory containing custom SHX fonts.
"""
print(f"Input DWG: {input_dwg}")
print(f"Output PDF: {output_pdf}")
print(f"Fonts directory: {fonts_dir}")
# Load the DWG file
try:
image = cad.Image.load(input_dwg)
print("Successfully loaded DWG file.")
except Exception as e:
print(f"Error loading DWG file: {e}")
return
# Create an instance of CadRasterizationOptions
rasterization_options = cad.imageoptions.CadRasterizationOptions()
# Set page size to match drawing size and disable scaling to preserve coordinates
rasterization_options.no_scaling = True
rasterization_options.page_width = float(image.width)
rasterization_options.page_height = float(image.height)
rasterization_options.layouts = ["Model"]
# Set to color mode. 1 corresponds to USE_OBJECT_COLOR.
# We use the integer value directly as the enum type is not exposed in a public module.
rasterization_options.draw_type = 1
# Find and set SHX fonts
shx_font_files = find_shx_files(fonts_dir)
if shx_font_files:
print(f"Found {len(shx_font_files)} SHX font files.")
rasterization_options.shx_fonts = shx_font_files
else:
print("Warning: No SHX font files found in the specified directory.")
# Create an instance of PdfOptions
pdf_options = cad.imageoptions.PdfOptions()
pdf_options.vector_rasterization_options = rasterization_options
# Save the PDF
try:
image.save(output_pdf, pdf_options)
print(f"Successfully converted to PDF: {output_pdf}")
except Exception as e:
print(f"Error saving PDF file: {e}")
finally:
# Dispose image - The python wrapper seems to handle this automatically.
# image.dispose()
print("Image resources are managed automatically.")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Convert CAD drawing to PDF with custom fonts.")
parser.add_argument("input_file", help="Path to the input CAD file (e.g., DWG, DXF).")
args = parser.parse_args()
input_file_path = args.input_file
# Define other paths
workspace_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
fonts_folder_path = os.path.join(workspace_root, '03_Python_OpenSource_DXF', 'fonts')
# Generate output file path based on input file name
base_name = os.path.basename(input_file_path)
file_name, _ = os.path.splitext(base_name)
output_file_path = os.path.join(os.path.dirname(__file__), f'{file_name}_output.pdf')
# Check if files/folders exist
if not os.path.exists(input_file_path):
print(f"Error: Input file not found at {input_file_path}")
elif not os.path.isdir(fonts_folder_path):
print(f"Error: Fonts directory not found at {fonts_folder_path}")
else:
print_cad_to_pdf(input_file_path, output_file_path, fonts_folder_path)