QR-коды и штрихкоды
Генерация QR-кодов и 1D штрих-кодов непосредственно как PDF-документов. Генерация штрихкодов вынесена за feature-флаг для сохранения легковесности основной библиотеки.
Требуется feature-флаг: barcodes
# Cargo.toml
[dependencies]
pdf_oxide = { version = "0.3", features = ["barcodes"] }
Быстрый пример
Python
from pdf_oxide import Pdf
# QR code
pdf = Pdf.from_qrcode("https://example.com")
pdf.save("qrcode.pdf")
# Barcode
pdf = Pdf.from_barcode("Code128", "ABC-12345")
pdf.save("barcode.pdf")
Rust
use pdf_oxide::api::Pdf;
// QR code
let pdf = Pdf::from_qrcode("https://example.com")?;
pdf.save("qrcode.pdf")?;
// Barcode
use pdf_oxide::writer::barcode::BarcodeType;
let pdf = Pdf::from_barcode(BarcodeType::Code128, "ABC-12345")?;
pdf.save("barcode.pdf")?;
Полный справочник API
Генерация QR-кодов
Pdf::from_qrcode(data) – Default QR Code
Создаёт одностраничный PDF с QR-кодом размером 300px.
Rust:
use pdf_oxide::api::Pdf;
let pdf = Pdf::from_qrcode("https://example.com")?;
pdf.save("qr.pdf")?;
Python:
from pdf_oxide import Pdf
pdf = Pdf.from_qrcode("https://example.com")
pdf.save("qr.pdf")
Python Signature:
Pdf.from_qrcode(data: str) -> Pdf
Pdf::from_qrcode_with_options(data, options) – Custom QR Code
Полный контроль над размером, уровнем коррекции ошибок, цветами и зоной тишины.
Rust:
use pdf_oxide::api::Pdf;
use pdf_oxide::writer::barcode::{QrCodeOptions, QrErrorCorrection};
let options = QrCodeOptions::new()
.size(400)
.error_correction(QrErrorCorrection::High)
.quiet_zone(6)
.foreground(0, 0, 128, 255) // Navy blue
.background(255, 255, 255, 255); // White
let pdf = Pdf::from_qrcode_with_options("https://example.com", &options)?;
pdf.save("custom_qr.pdf")?;
QrCodeOptions – QR Configuration
| Method | Default | Description |
|---|---|---|
.size(px) |
200 | QR code size in pixels |
.error_correction(level) |
Medium |
Уровень коррекции ошибок |
.quiet_zone(modules) |
4 | Ширина рамки в модулях |
.foreground(r, g, b, a) |
Black (0,0,0,255) | Module color (RGBA) |
.background(r, g, b, a) |
White (255,255,255,255) | Фон color (RGBA) |
QrErrorCorrection Enum
| Variant | Recovery Capacity | Use Case |
|---|---|---|
Low |
~7% | Максимальная плотность данных |
Medium |
~15% | Общего назначения (по умолчанию) |
Quartile |
~25% | Этикетки, которые могут быть повреждены |
High |
~30% | Industrial / harsh environments |
Генерация одномерных штрихкодов
Pdf::from_barcode(barcode_type, data) – Default Barcode
Создаёт одностраничный PDF со штрихкодом стандартного размера (200x80).
Rust:
use pdf_oxide::api::Pdf;
use pdf_oxide::writer::barcode::BarcodeType;
let pdf = Pdf::from_barcode(BarcodeType::Ean13, "5901234123457")?;
pdf.save("product.pdf")?;
Python:
from pdf_oxide import Pdf
# Barcode type as string: "code128", "ean13", "upca", "code39", "ean8", "itf"
pdf = Pdf.from_barcode("ean13", "5901234123457")
pdf.save("product.pdf")
Python Signature:
Pdf.from_barcode(
barcode_type: str, # "code128" | "ean13" | "upca" | "code39" | "ean8" | "itf"
data: str
) -> Pdf
Pdf::from_barcode_with_options(barcode_type, data, options) – Custom Barcode
Полный контроль над размерами и цветами штрихкода.
Rust:
use pdf_oxide::api::Pdf;
use pdf_oxide::writer::barcode::{BarcodeType, BarcodeOptions};
let options = BarcodeOptions::new()
.width(400)
.height(120)
.foreground(0, 0, 0, 255)
.background(255, 255, 255, 255);
let pdf = Pdf::from_barcode_with_options(
BarcodeType::Code128,
"SHIP-2025-00042",
&options,
)?;
pdf.save("shipping_label.pdf")?;
BarcodeOptions – 1D Configuration
| Method | Default | Description |
|---|---|---|
.width(px) |
200 | Barcode width in pixels |
.height(px) |
80 | Barcode height in pixels |
.foreground(r, g, b, a) |
Black (0,0,0,255) | Bar color (RGBA) |
.background(r, g, b, a) |
White (255,255,255,255) | Фон color (RGBA) |
.show_text(bool) |
false | Show human-readable text |
BarcodeType Enum
| Variant | Name | Data Format |
|---|---|---|
Code128 |
Code 128 | Alphanumeric (auto-selects A/B/C) |
Code39 |
Code 39 | Uppercase alphanumeric + symbols |
Ean13 |
EAN-13 | 13 digits (European Article Number) |
Ean8 |
EAN-8 | 8 digits (compact EAN) |
UpcA |
UPC-A | 11-12 digits (Universal Product Code) |
Itf |
Interleaved 2 of 5 | Numeric pairs (even digit count) |
Code93 |
Code 93 | Alphanumeric (compact) |
Codabar |
Codabar | Digits + special chars (A-D start/stop) |
Низкоуровневый BarcodeGenerator
Для генерации изображений штрихкодов без создания полного PDF (например, для встраивания в существующий документ):
use pdf_oxide::writer::barcode::{BarcodeGenerator, BarcodeType, BarcodeOptions, QrCodeOptions};
// Generate QR code as PNG bytes
let qr_png = BarcodeGenerator::generate_qr(
"https://example.com",
&QrCodeOptions::default().size(256),
)?;
// Generate QR code with simple API
let qr_png = BarcodeGenerator::generate_qr_simple("https://example.com", 200)?;
// Generate 1D barcode as PNG bytes
let barcode_png = BarcodeGenerator::generate_1d(
BarcodeType::Code128,
"ABC123",
&BarcodeOptions::default().width(300).height(100),
)?;
// Convenience methods
let code128_png = BarcodeGenerator::generate_code128("DATA", 200, 80)?;
let ean13_png = BarcodeGenerator::generate_ean13("5901234123457", 200, 80)?;
Использование PdfBuilder со штрихкодами
PdfBuilder предоставляет fluent-интерфейс для настройки размера страницы и метаданных документа перед генерацией PDF со штрихкодами.
use pdf_oxide::api::PdfBuilder;
use pdf_oxide::writer::PageSize;
use pdf_oxide::writer::barcode::{BarcodeType, QrCodeOptions, QrErrorCorrection};
// QR code with custom page size
let pdf = PdfBuilder::new()
.title("WiFi Access")
.page_size(PageSize::Custom(300.0, 300.0))
.from_qrcode("WIFI:T:WPA;S:MyNetwork;P:secret123;;")?;
pdf.save("wifi_qr.pdf")?;
// Barcode with metadata
let pdf = PdfBuilder::new()
.title("Product Label")
.author("Warehouse System")
.from_barcode(BarcodeType::Ean13, "5901234123457")?;
pdf.save("label.pdf")?;
Продвинутые примеры
Этикетка доставки с несколькими штрихкодами
use pdf_oxide::writer::barcode::{BarcodeGenerator, BarcodeType, BarcodeOptions, QrCodeOptions};
use pdf_oxide::writer::{PdfWriter, PdfWriterConfig};
use pdf_oxide::geometry::Rect;
// Generate barcode images
let tracking_barcode = BarcodeGenerator::generate_code128(
"1Z999AA10123456784",
300,
80,
)?;
let qr_bytes = BarcodeGenerator::generate_qr(
"https://track.example.com/1Z999AA10123456784",
&QrCodeOptions::new().size(200).error_correction(QrErrorCorrection::Medium),
)?;
// These PNG bytes can then be embedded in a PDF using the image APIs
Пакетная генерация этикеток продуктов
use pdf_oxide::api::Pdf;
use pdf_oxide::writer::barcode::BarcodeType;
let products = vec![
("5901234123457", "Widget A"),
("4006381333931", "Widget B"),
("0012345678905", "Widget C"),
];
for (ean, name) in products {
let pdf = Pdf::from_barcode(BarcodeType::Ean13, ean)?;
pdf.save(format!("label_{}.pdf", name.to_lowercase().replace(' ', "_")))?;
}
Python: генерация и сохранение QR-кодов
from pdf_oxide import Pdf
urls = [
"https://example.com/product/1",
"https://example.com/product/2",
"https://example.com/product/3",
]
for i, url in enumerate(urls):
pdf = Pdf.from_qrcode(url)
pdf.save(f"qr_product_{i + 1}.pdf")
Python: пакетная генерация штрихкодов
from pdf_oxide import Pdf
items = [
("code128", "SHIP-00001"),
("code128", "SHIP-00002"),
("ean13", "5901234123457"),
("upca", "012345678905"),
]
for barcode_type, data in items:
pdf = Pdf.from_barcode(barcode_type, data)
pdf.save(f"barcode_{data}.pdf")
Feature-флаг
Функция barcodes подключает две дополнительных зависимости:
barcoders– 1D barcode encodingqrcode– QR code encoding
Без feature-флага все методы штрихкодов возвращают сообщение об ошибке, указывающее на необходимость данной функции.
// Without the barcodes feature enabled:
let result = Pdf::from_qrcode("test");
// Returns Err("QR code generation requires the 'barcodes' feature")
Связанные страницы
- Fluent API PdfBuilder — настройка размера страницы и метаданных для PDF со штрихкодами
- Создание из изображений — встраивание PNG-штрихкодов в PDF
- Графика, паттерны и заливки — низкоуровневое рисование для пользовательских макетов этикеток
- Типы и перечисления — подробности перечисления BarcodeType