Вопрос Python Как создать плашечные цвета, которые регистрируются как порезы в PDF?Python

Программы на Python
Anonymous
Вопрос Python Как создать плашечные цвета, которые регистрируются как порезы в PDF?

Сообщение Anonymous »

Я работаю над проектом, который требует создания линии разреза вокруг изображения, и у меня возникают трудности с ее регистрацией в качестве фактической линии разреза в любой из программ RIP, таких как Versaworks или Flexi.
Я попробовал несколько различных библиотек Python, чтобы помочь с этим, но не смог заставить это работать. Я хотел бы создать линию пореза в виде плашечного цвета с именем CutContour, как мы делаем в Illustrator, но по какой-то причине она не регистрируется при экспорте.
Я пробовал подушку, элемент Tree, Inkscape, Scribus - безрезультатно.
import subprocess
import os
import xml.etree.ElementTree as ET
import cv2
import numpy as np
from PIL import Image

def convert_png_to_svg(input_image_path, output_svg_path):
try:
subprocess.run(['C:\\Program Files\\Inkscape\\bin\\inkscape.exe', input_image_path, '--export-type=svg', '--export-filename', output_svg_path], check=True)
if os.path.exists(output_svg_path):
print(f"SVG file created: {os.path.abspath(output_svg_path)}")
else:
print(f"Error: SVG file was not created: {output_svg_path}")
except subprocess.CalledProcessError as e:
print(f"Error running Inkscape: {e}")
except FileNotFoundError:
print("Inkscape not found. Make sure it's installed at the specified path.")

def remove_small_objects(mask, min_size):
num_labels, labels, stats, _ = cv2.connectedComponentsWithStats(mask, connectivity=8)
for i in range(1, num_labels):
if stats[i, cv2.CC_STAT_AREA] < min_size:
mask[labels == i] = 0
return mask

def add_contour_to_svg(input_image_path, svg_path, output_svg_path, border_size, padding):
# Open the original image
img = Image.open(input_image_path).convert("RGBA")

# Add initial padding to the original image
padded_size = (img.width + 2 * padding, img.height + 2 * padding)
padded_img = Image.new("RGBA", padded_size, (0, 0, 0, 0))
padded_img.paste(img, (padding, padding))

# Convert to numpy array
img_np = np.array(padded_img)

# Create an alpha mask
alpha = img_np[:, :, 3]

# Create a binary mask
mask = (alpha > 0).astype(np.uint8) * 255

# Remove small objects (smaller than 1px)
mask = remove_small_objects(mask, 1)

# Find contours using OpenCV
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# Find the outer contour
outer_contour = max(contours, key=cv2.contourArea)

# Create a new mask for the border
border_mask = np.zeros_like(mask)

# Draw the contour on the border mask with a thicker stroke
cv2.drawContours(border_mask, [outer_contour], -1, 255, border_size)

# Find the contours of the border mask
border_contours, _ = cv2.findContours(border_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
border_contour = max(border_contours, key=cv2.contourArea)

# Parse the SVG
tree = ET.parse(svg_path)
root = tree.getroot()
ns = {'svg': 'http://www.w3.org/2000/svg'}

# Create a new layer for the cut path
layer = ET.SubElement(root, 'g', {
'id': 'cut_layer',
'inkscape:groupmode': 'layer',
'inkscape:label': 'CutContour'
})

# Create the cut path
path_data = 'M ' + ' '.join(f'{px},{py}' for px, py in [point[0] for point in border_contour]) + ' Z'
ET.SubElement(layer, 'path', {
'd': path_data,
'fill': 'none',
'stroke': '#EC008C',
'stroke-width': str(border_size)
})

# Save the modified SVG
tree.write(output_svg_path)
print(f"Modified SVG with contour saved as: {output_svg_path}")

def export_svg_to_pdf(svg_path, output_pdf_path):
try:
subprocess.run(['C:\\Program Files\\Inkscape\\bin\\inkscape.exe', svg_path, '--export-type=pdf', '--export-filename', output_pdf_path], check=True)
if os.path.exists(output_pdf_path):
print(f"PDF file created: {os.path.abspath(output_pdf_path)}")
else:
print(f"Error: PDF file was not created: {output_pdf_path}")
except subprocess.CalledProcessError as e:
print(f"Error running Inkscape: {e}")
except FileNotFoundError:
print("Inkscape not found. Make sure it's installed at the specified path.")

# Input image path
input_image_path = '2.png'
# Output SVG paths
output_svg_path = '2_converted.svg'
modified_svg_path = '2_with_cut.svg'
# Output PDF path
output_pdf_path = '2_final.pdf'
# Border size (pixels)
border_size = 1
# Padding size (pixels)
padding = 10

# Step 1: Convert PNG to SVG using Inkscape
convert_png_to_svg(input_image_path, output_svg_path)

# Step 2: Add cut path and spot color to the SVG
add_contour_to_svg(input_image_path, output_svg_path, modified_svg_path, border_size, padding)

# Step 3: Export the modified SVG to PDF using Inkscape
export_svg_to_pdf(modified_svg_path, output_pdf_path)


Подробнее здесь: https://stackoverflow.com/questions/788 ... nes-in-pdf

Вернуться в «Python»