Вопрос 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)

Исправлено. Этот код добавит отступную рамку и линию пореза к любому файлу, который регистрируется как в Flexi, так и в Versaworks. На данный момент вам необходимо иметь файл с именем 2.png в каталоге вашего проекта, но вы можете легко использовать его.
import numpy as np
from PIL import Image, ImageDraw, ImageFilter
import cv2
import os
from reportlab.pdfgen import canvas
from reportlab.lib.colors import PCMYKColorSep
from reportlab.lib.utils import ImageReader

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 create_image_with_border(input_image_path, border_size, corner_radius):
# Open the original image
img = Image.open(input_image_path).convert("RGBA")

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

# Remove pixels with opacity lower than 60%
img_np[img_np[:, :, 3] < 153] = [0, 0, 0, 0]

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

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

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

# Convert mask to PIL Image
mask_img = Image.fromarray(mask)

# Calculate new size with padding
padding = max(border_size * 3, corner_radius * 2)
new_size = (img_np.shape[1] + padding * 2, img_np.shape[0] + padding * 2)

# Create a new image with extra space for the border
img_with_border = Image.new('RGBA', new_size, (0, 0, 0, 0))

# Create a mask for the contour
contour_mask = Image.new('L', new_size, 0)
paste_position = (padding, padding)
contour_mask.paste(mask_img, paste_position)

# Apply corner rounding
contour_mask = contour_mask.filter(ImageFilter.GaussianBlur(radius=corner_radius / 2))
contour_mask = contour_mask.point(lambda x: 255 if x > 128 else 0)

# Create the contour border
contour_border = contour_mask.filter(ImageFilter.GaussianBlur(radius=border_size / 2))
contour_border = contour_border.point(lambda x: 255 if x > 0 else 0)

# Create a white layer for the border
white_layer = Image.new('RGBA', new_size, (255, 255, 255, 255))

# Paste the white border behind the image
img_with_border.paste(white_layer, (0, 0), contour_border)

# Paste the original image on top
img_with_border.paste(Image.fromarray(img_np), paste_position, Image.fromarray(mask))

return img_with_border

def create_contour(image):
# Convert image to numpy array
img_np = np.array(image)

# Create a binary mask
mask = (img_np[:, :, 3] > 0).astype(np.uint8) * 255

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

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

return outer_contour

def create_pdf_with_spot_color(image, contour, pdf_path, cutline_offset):
# Get image dimensions
img_width, img_height = image.size

# Create a new PDF canvas
c = canvas.Canvas(pdf_path, pagesize=(img_width + 2 * cutline_offset, img_height + 2 * cutline_offset))

# Define the spot color for the cut contour
cut_contour_spot = PCMYKColorSep(0.0, 100.0, 91.0, 0.0, spotName='CutContour', density=100)

# Draw the image
c.drawImage(ImageReader(image), cutline_offset, cutline_offset, img_width, img_height, mask='auto')

# Set the spot color
c.setStrokeColor(cut_contour_spot)

# Draw the contour path
c.setLineWidth(1)
path = c.beginPath()

# Start the path with a move to command
path.moveTo(contour[0][0][0] + cutline_offset,
(img_height + 2 * cutline_offset) - (contour[0][0][1] + cutline_offset))

# Draw the contour path
for point in contour[1:]:
px, py = point[0]
path.lineTo(px + cutline_offset,
(img_height + 2 * cutline_offset) - (py + cutline_offset)) # Adjust for coordinate system

path.close()
c.drawPath(path)

# Save the PDF
c.save()

print(f"PDF with spot color cut contour created: {pdf_path}")

# Input image path
input_image_path = '2.png'

# Output PDF path
output_pdf_path = 'cut_contour_spot_color.pdf'

# Border size (pixels)
border_size = 12

# Corner radius (pixels)
corner_radius = 7

# Cutline offset (distance from border to cutline)
cutline_offset = 1

# Create image with rounded contour padding border
img_with_border = create_image_with_border(input_image_path, border_size, corner_radius)

# Create contour from image with border
contour = create_contour(img_with_border)

# Create the PDF with the spot color cut contour
create_pdf_with_spot_color(img_with_border, contour, output_pdf_path, cutline_offset)

print(f"PDF created: {os.path.abspath(output_pdf_path)}")


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

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