QR 코드와 바코드
QR 코드와 1D 바코드를 PDF 문서로 직접 생성하거나, 독립적인 PNG/SVG 이미지로 만들거나, 기존 PDF의 페이지 위에 배치할 수 있습니다. 바코드 생성은 핵심 라이브러리를 가볍게 유지하기 위해 기능 플래그 뒤에 숨겨져 있습니다.
바인딩 지원 범위. 바코드 관련 인터페이스는 크게 두 가지로 구분됩니다.
- 원샷 PDF 생성자(
Pdf::from_qrcode/Pdf::from_barcode)와 저수준BarcodeGenerator— Rust에서만 제공됩니다.- 바코드 이미지 핸들 계열(
generate_qr_code,generate_barcode,add_barcode_to_page). C ABI의pdf_generate_qr_code/pdf_generate_barcode/pdf_add_barcode_to_page함수에 기반하며 — **Swift, Go, C#**에서 제공되고 FFI를 통해 C/C++에서 직접 호출할 수도 있습니다.- SVG 생성기(
generate_qr_svg/generate_barcode_svg) — Python과 Rust에서 제공됩니다.아래의 각 메서드에는 실제로 그것을 제공하는 언어가 표시되어 있습니다. 표시되지 않은 바인딩에 해당 메서드가 존재한다고 가정하지 마십시오.
필요한 기능 플래그: barcodes
# Cargo.toml
[dependencies]
pdf_oxide = { version = "0.3", features = ["barcodes"] }
QR 코드를 PDF로 생성하려면?
Rust에서 가장 빠른 방법은 원샷 Pdf::from_qrcode 생성자입니다. pdf_oxide가 QR 코드를 단일 페이지 PDF에 기록하므로 바로 저장할 수 있습니다.
Rust:
use pdf_oxide::api::Pdf;
fn main() -> Result<(), Box<dyn std::error::Error>> {
// QR code (300px) -> single-page PDF
let pdf = Pdf::from_qrcode("https://example.com")?;
pdf.save("qrcode.pdf")?;
// 1D barcode -> single-page PDF
use pdf_oxide::writer::barcode::BarcodeType;
let pdf = Pdf::from_barcode(BarcodeType::Code128, "ABC-12345")?;
pdf.save("barcode.pdf")?;
Ok(())
}
PDF 대신 바코드 이미지(PNG/SVG)를 생성하려면?
인코딩된 글리프를 이미지로 — 기존 문서에 삽입하거나, 웹 프런트엔드로 전달하거나, 라벨에 인쇄하기 위해 — 얻고 싶다면 이미지 핸들 계열이나 SVG 생성기를 사용하세요. 정규 메서드 이름은 generate_qr_code와 generate_barcode입니다(이전 이름인 generate_qr / generate_code는 공개 인터페이스에 포함되지 않습니다).
Swift(BarcodeImage.generateQrCode, BarcodeImage.generateBarcode):
import PdfOxide
// QR code. errorCorrection: 0=L 1=M 2=Q 3=H. sizePx: module-grid pixel size.
let qr = try BarcodeImage.generateQrCode("https://example.com",
errorCorrection: 1, sizePx: 256)
let pngBytes = try qr.imagePng(sizePx: 256) // [UInt8]
let svg = try qr.svg(sizePx: 256) // String
qr.close()
// 1D barcode. format: 0=Code128 1=Code39 2=EAN13 3=EAN8 4=UPCA 5=ITF 6=Code93 7=Codabar.
let bc = try BarcodeImage.generateBarcode("5901234123457", format: 2, sizePx: 256)
let barcodePng = try bc.imagePng(sizePx: 256)
bc.close()
Go(GenerateQRCode, GenerateBarcode):
package main
import (
"os"
pdfoxide "github.com/yfedoseev/pdf_oxide/go"
)
func main() {
// QR code. errorCorrection: 0=Low 1=Medium 2=Quartile 3=High.
qr, err := pdfoxide.GenerateQRCode("https://example.com", 1, 256)
if err != nil {
panic(err)
}
defer qr.Close()
svg, _ := qr.SVGData()
_ = os.WriteFile("qr.svg", []byte(svg), 0o644)
// 1D barcode. format: 0=Code128 1=Code39 2=EAN13 3=EAN8 4=UPCA 5=ITF 6=Code93 7=Codabar.
bc, err := pdfoxide.GenerateBarcode("5901234123457", 2, 300)
if err != nil {
panic(err)
}
defer bc.Close()
png, _ := bc.PNGData()
_ = os.WriteFile("ean13.png", png, 0o644)
}
C#(Barcode.GenerateQrCode, Barcode.Generate):
using PdfOxide;
// QR code. errorCorrection: 0=L 1=M 2=Q 3=H. sizePx default 300.
using var qr = Barcode.GenerateQrCode("https://example.com", errorCorrection: 1, sizePx: 256);
byte[] qrPng = qr.ToPng(256);
string qrSvg = qr.ToSvg();
// 1D barcode. BarcodeFormat: Code128, Code39, Ean13, Ean8, UpcA, Itf.
using var bc = Barcode.Generate("5901234123457", BarcodeFormat.Ean13, sizePx: 300);
byte[] eanPng = bc.ToPng(300);
Python(generate_qr_svg, generate_barcode_svg — SVG 전용):
import pdf_oxide
# QR code SVG. error_correction: 0=Low, 1=Medium, 2=Quartile, 3=High. size in px.
qr_svg = pdf_oxide.generate_qr_svg("https://example.com", 1, 256)
with open("qr.svg", "w") as f:
f.write(qr_svg)
# 1D barcode SVG. barcode_type: 0=Code128, 1=Code39, 2=EAN13, 3=EAN8,
# 4=UPCA, 5=ITF, 6=Code93, 7=Codabar.
ean_svg = pdf_oxide.generate_barcode_svg(2, "5901234123457")
with open("ean13.svg", "w") as f:
f.write(ean_svg)
기존 PDF 페이지에 바코드를 추가하려면?
add_barcode_to_page를 사용하면 생성한 바코드 이미지를 DocumentEditor의 (0부터 시작하는) 페이지 위 지정한 위치와 크기에 배치한 다음 저장할 수 있습니다. 이는 Swift에서는 DocumentEditor.addBarcodeToPage로 관용적으로 제공되며, C ABI에서는 pdf_add_barcode_to_page로 직접 제공됩니다. 이 기능이 의존하는 이미지 핸들 계열은 Go/C# 에디터 클래스에 래핑되어 있지 않으므로, 제자리 배치에는 Swift를 사용하거나(또는 C/C++에서 C ABI를 호출) 하십시오.
Swift(DocumentEditor.addBarcodeToPage):
import PdfOxide
let editor = try DocumentEditor.openFromBytes(try Data(contentsOf: inputURL).map { $0 })
// Generate the barcode image, then stamp it onto page 0 (PDF user-space points).
let qr = try BarcodeImage.generateQrCode("https://example.com/track/42", sizePx: 128)
try editor.addBarcodeToPage(0, qr, x: 36, y: 36, width: 96, height: 96)
let outBytes = try editor.saveToBytes()
qr.close()
editor.close()
C ABI(pdf_add_barcode_to_page):
#include "pdf_oxide.h"
int err = 0;
// Build a barcode handle (QR shown; use pdf_generate_barcode for 1D).
FfiBarcodeImage *qr = pdf_generate_qr_code("https://example.com/track/42",
/*error_correction=*/1,
/*size_px=*/128, &err);
// Place it on page 0 at (x, y) sized width x height (PDF user-space points).
pdf_add_barcode_to_page(editor, /*page_index=*/0, qr,
/*x=*/36.0f, /*y=*/36.0f,
/*width=*/96.0f, /*height=*/96.0f, &err);
pdf_barcode_free(qr);
메서드 시그니처
원샷 PDF 생성자 — Rust 전용
// QR code, 300px default size:
Pdf::from_qrcode(data: &str) -> Result<Pdf>
Pdf::from_qrcode_with_options(data: &str, options: &QrCodeOptions) -> Result<Pdf>
// 1D barcode, 200x80 default size:
Pdf::from_barcode(barcode_type: BarcodeType, data: &str) -> Result<Pdf>
Pdf::from_barcode_with_options(barcode_type: BarcodeType, data: &str,
options: &BarcodeOptions) -> Result<Pdf>
바코드 이미지 핸들 계열 — Swift / Go / C# / C ABI
| 언어 | QR 생성기 | 1D 생성기 | 페이지에 배치 |
|---|---|---|---|
| Swift | BarcodeImage.generateQrCode(_ data:, errorCorrection: Int32 = 1, sizePx: Int32 = 256) |
BarcodeImage.generateBarcode(_ data:, format: Int32, sizePx: Int32 = 256) |
DocumentEditor.addBarcodeToPage(_ page:, _ barcode:, x:, y:, width:, height:) |
| Go | GenerateQRCode(data string, errorCorrection int, sizePx int) (*BarcodeImage, error) |
GenerateBarcode(data string, format int, sizePx int) (*BarcodeImage, error) |
— (에디터에 래핑되지 않음) |
| C# | Barcode.GenerateQrCode(string data, int errorCorrection = 1, int sizePx = 300) |
Barcode.Generate(string data, BarcodeFormat format = Code128, int sizePx = 300) |
— (에디터에 래핑되지 않음) |
| C ABI | pdf_generate_qr_code(const char *data, int32_t error_correction, int32_t size_px, int32_t *error_code) |
pdf_generate_barcode(const char *data, int32_t format, int32_t size_px, int32_t *error_code) |
pdf_add_barcode_to_page(DocumentEditor *doc, int32_t page_index, const FfiBarcodeImage *barcode, float x, float y, float width, float height, int32_t *error_code) |
바코드 핸들을 확보하면 그 페이로드를 읽고 렌더링할 수 있습니다.
| 작업 | Swift | Go | C# | C ABI |
|---|---|---|---|---|
| PNG 바이트 | imagePng(sizePx:) |
PNGData() |
ToPng(sizePx) |
pdf_barcode_get_image_png |
| SVG 문자열 | svg(sizePx:) |
SVGData() |
ToSvg() |
pdf_barcode_get_svg |
| 디코딩된 데이터 | data() |
SourceData() |
Data |
pdf_barcode_get_data |
| 형식 코드 | format() |
— | Format |
pdf_barcode_get_format |
| 핸들 해제 | close() |
Close() |
Dispose() |
pdf_barcode_free |
SVG 생성기 — Python / Rust
# Python free functions (require the barcodes feature in the wheel):
generate_qr_svg(data: str, error_correction: int, size: int) -> str
generate_barcode_svg(barcode_type: int, data: str) -> str
Rust: 전체 API 참조
QR 코드 생성
Pdf::from_qrcode(data) — 기본 QR 코드
300px QR 코드를 담은 단일 페이지 PDF를 생성합니다.
use pdf_oxide::api::Pdf;
let pdf = Pdf::from_qrcode("https://example.com")?;
pdf.save("qr.pdf")?;
Pdf::from_qrcode_with_options(data, options) — 사용자 지정 QR 코드
크기, 오류 정정, 색상, 정적 영역(quiet zone)을 완전히 제어합니다.
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 설정
| 메서드 | 기본값 | 설명 |
|---|---|---|
.size(px) |
200 | QR 코드 크기(픽셀) |
.error_correction(level) |
Medium |
오류 정정 수준 |
.quiet_zone(modules) |
4 | 모듈 단위의 테두리 너비 |
.foreground(r, g, b, a) |
Black (0,0,0,255) | 모듈 색상(RGBA) |
.background(r, g, b, a) |
White (255,255,255,255) | 배경 색상(RGBA) |
QrErrorCorrection 열거형
| 변형 | 복구 용량 | 사용 사례 | 정수(FFI) |
|---|---|---|---|
Low |
약 7% | 최대 데이터 밀도 | 0 |
Medium |
약 15% | 범용(기본값) | 1 |
Quartile |
약 25% | 손상될 수 있는 라벨 | 2 |
High |
약 30% | 산업용 / 가혹한 환경 | 3 |
1D 바코드 생성
Pdf::from_barcode(barcode_type, data) — 기본 바코드
기본 크기(200x80)의 바코드를 담은 단일 페이지 PDF를 생성합니다.
use pdf_oxide::api::Pdf;
use pdf_oxide::writer::barcode::BarcodeType;
let pdf = Pdf::from_barcode(BarcodeType::Ean13, "5901234123457")?;
pdf.save("product.pdf")?;
Pdf::from_barcode_with_options(barcode_type, data, options) — 사용자 지정 바코드
바코드의 치수와 색상을 완전히 제어합니다.
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 설정
| 메서드 | 기본값 | 설명 |
|---|---|---|
.width(px) |
200 | 바코드 너비(픽셀) |
.height(px) |
80 | 바코드 높이(픽셀) |
.foreground(r, g, b, a) |
Black (0,0,0,255) | 막대 색상(RGBA) |
.background(r, g, b, a) |
White (255,255,255,255) | 배경 색상(RGBA) |
.show_text(bool) |
false | 사람이 읽을 수 있는 텍스트 표시 |
BarcodeType 열거형
| 변형 | 이름 | 데이터 형식 | 정수(FFI) |
|---|---|---|---|
Code128 |
Code 128 | 영숫자(A/B/C 자동 선택) | 0 |
Code39 |
Code 39 | 대문자 영숫자 + 기호 | 1 |
Ean13 |
EAN-13 | 13자리 숫자(European Article Number) | 2 |
Ean8 |
EAN-8 | 8자리 숫자(컴팩트 EAN) | 3 |
UpcA |
UPC-A | 11~12자리 숫자(Universal Product Code) | 4 |
Itf |
Interleaved 2 of 5 | 숫자 쌍(짝수 자릿수) | 5 |
Code93 |
Code 93 | 영숫자(컴팩트) | 6 |
Codabar |
Codabar | 숫자 + 특수 문자(A-D 시작/종료) | 7 |
C ABI의
pdf_generate_barcode와 Go/Swift/C# 래퍼는 위 표의 정수(FFI) 열로 심볼로지를 선택합니다. C#의BarcodeFormat열거형은 현재Code128~Itf(0~5)를 제공합니다.
저수준 BarcodeGenerator — Rust 전용
완전한 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 as an SVG string
let qr_svg = BarcodeGenerator::generate_qr_svg(
"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),
)?;
// Generate 1D barcode as an SVG string
let barcode_svg = BarcodeGenerator::generate_1d_svg(
BarcodeType::Code128,
"ABC123",
&BarcodeOptions::default(),
)?;
// Convenience methods
let code128_png = BarcodeGenerator::generate_code128("DATA", 200, 80)?;
let ean13_png = BarcodeGenerator::generate_ean13("5901234123457", 200, 80)?;
바코드와 함께 PdfBuilder 사용 — Rust 전용
PdfBuilder는 바코드 PDF를 생성하기 전에 페이지 크기와 문서 메타데이터를 설정하기 위한 플루언트 인터페이스를 제공합니다.
use pdf_oxide::api::PdfBuilder;
use pdf_oxide::writer::PageSize;
use pdf_oxide::writer::barcode::BarcodeType;
// 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")?;
고급 예제
여러 바코드가 있는 배송 라벨 (Rust)
use pdf_oxide::writer::barcode::{BarcodeGenerator, QrCodeOptions, QrErrorCorrection};
// Generate barcode images, then embed via the image APIs.
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),
)?;
// `tracking_barcode` and `qr_bytes` are PNG byte vectors ready to embed.
제품 라벨 일괄 생성 (Rust)
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(' ', "_")))?;
}
바코드 SVG 일괄 생성 (Python)
import pdf_oxide
items = [
(0, "SHIP-00001"), # Code128
(0, "SHIP-00002"), # Code128
(2, "5901234123457"), # EAN-13
(4, "012345678905"), # UPC-A
]
for barcode_type, data in items:
svg = pdf_oxide.generate_barcode_svg(barcode_type, data)
with open(f"barcode_{data}.svg", "w") as f:
f.write(svg)
모든 라벨에 추적용 QR 코드 찍기 (Swift)
import PdfOxide
let editor = try DocumentEditor.openFromBytes(labelTemplateBytes)
let pageCount = try editor.pageCount()
for page in 0..<pageCount {
let qr = try BarcodeImage.generateQrCode("https://track.example.com/\(page)", sizePx: 128)
try editor.addBarcodeToPage(page, qr, x: 420, y: 700, width: 80, height: 80)
qr.close()
}
let stamped = try editor.saveToBytes()
editor.close()
기능 플래그
barcodes 기능은 두 개의 추가 의존성을 가져옵니다.
barcoders— 1D 바코드 인코딩qrcode— QR 코드 인코딩
기능 플래그가 없으면 모든 바코드 메서드는 해당 기능이 필요하다는 오류를 반환합니다.
// Without the barcodes feature enabled:
let result = Pdf::from_qrcode("test");
// Returns Err("QR code generation requires the 'barcodes' feature")
자주 묻는 질문
Q: 문서에 generate_qr와 generate_code가 언급되는데, 그것이 맞는 이름인가요?
A: 아닙니다. 정규 공개 메서드 이름은 generate_qr_code와 generate_barcode입니다(C ABI의 pdf_generate_qr_code / pdf_generate_barcode에 기반). Rust 내부에서 BarcodeGenerator의 저수준 헬퍼는 generate_qr와 generate_1d이지만, 이들은 Rust 내부 헬퍼이지 바인딩 간 공통 인터페이스가 아닙니다.
Q: Python이나 Node에서 네이티브 바코드를 생성할 수 있나요?
A: Python은 삽입하거나 래스터화할 수 있는 SVG 문자열을 반환하는 generate_qr_svg와 generate_barcode_svg를 제공합니다. PNG 핸들과 페이지 내 제자리 배치를 위해서는 Swift, Go, C# 바인딩을 사용하거나 C ABI를 직접 호출하세요. 네이티브 원샷 PDF 생성자(from_qrcode / from_barcode)는 Rust 전용입니다.
Q: 기존 PDF의 특정 위치에 바코드를 배치하려면?
A: 이미지 핸들(generate_qr_code / generate_barcode)을 생성한 다음 add_barcode_to_page(document, page_index, barcode, x, y, width, height)를 호출하세요. 좌표와 크기는 PDF 사용자 공간 포인트 단위이며 페이지 인덱스는 0부터 시작합니다. 이는 Swift에서 DocumentEditor.addBarcodeToPage로 래핑되어 있으며, C/C++에서는 pdf_add_barcode_to_page를 호출합니다.
Q: 생성 속도는 얼마나 빠른가요? A: pdf_oxide의 라이터는 벤치마크 코퍼스에서 평균 0.8ms, 100% 통과율로 텍스트를 추출하는 동일한 엔진 위에 구축되어 있으므로, QR이나 1D 바코드를 인코딩하고 페이지를 출력하는 작업은 일괄 작업에서도 사실상 즉각적으로 이루어집니다.
관련 페이지
- PdfBuilder 플루언트 API — 바코드 PDF의 페이지 크기와 메타데이터 구성
- 이미지로부터 생성 — 여러 콘텐츠가 있는 PDF에 바코드 PNG 삽입
- 그래픽, 패턴 및 셰이딩 — 사용자 지정 라벨 레이아웃을 위한 저수준 드로잉
- 타입과 열거형 —
BarcodeType열거형 세부 정보