IronBarcode를 사용하여 PDF 문서에 바코드를 생성하고 삽입하는 방법

C#을 사용하여 PDF에 바코드를 스탬프하는 방법

This article was translated from English: Does it need improvement?
Translated
View the article in English

IronBarcode의 CreateBarcode 메서드를 사용하여 C#에서 기존 PDF 문서에 바코드를 스탬프하고, 단일 페이지에는 StampToExistingPdfPage, 여러 페이지에는 StampToExistingPdfPages를 사용하여 좌표와 페이지 번호를 지정합니다.

빠른 시작: 생성된 바코드를 PDF 페이지에 스탬프

이 예제는 IronBarcode의 CreateBarcode를 사용하여 바코드를 생성하고 기존 PDF 페이지에 이를 스탬프하는 방법을 보여줍니다. PDF 경로, 위치 좌표 및 페이지 번호를 제공합니다.

  1. NuGet 패키지 관리자를 사용하여 https://www.nuget.org/packages/BarCode 설치하기

    PM > Install-Package BarCode
  2. 다음 코드 조각을 복사하여 실행하세요.

    IronBarCode.BarcodeWriter.CreateBarcode("https://my.site", IronBarCode.BarcodeEncoding.QRCode, 150, 150)
        .StampToExistingPdfPage("report.pdf", x: 50, y: 50, pageNumber: 1);
  3. 실제 운영 환경에서 테스트할 수 있도록 배포하세요.

    무료 체험판으로 오늘 프로젝트에서 IronBarcode 사용 시작하기

    arrow pointer

기존 PDF 페이지에 바코드를 어떻게 스탬프하나요?

Apart from exporting barcodes as PDF, IronBarcode enables stamping the GeneratedBarcode directly onto existing PDF documents. 이 기능은 기존 보고서, 송장, 양식에 추적 코드, 인벤토리 라벨, 문서 식별자를 추가할 때 유용합니다. 다음 코드 스니펫은 이 작업을 보여줍니다.

:path=/static-assets/barcode/content-code-examples/how-to/StampBarcodeOnExistingPdfPage.cs
using IronBarCode;

GeneratedBarcode myBarcode = BarcodeWriter.CreateBarcode("https://ironsoftware.com/csharp/barcode/", BarcodeEncoding.Code128, 200, 100);
myBarcode.StampToExistingPdfPage("pdf_file_path.pdf", x: 200, y: 100, 3, "password");
$vbLabelText   $csharpLabel

StampToExistingPdfPage에 필요한 매개변수는 무엇입니까?

코드 스니펫은 GeneratedBarcode 객체와 함께 StampToExistingPdfPage() 메서드를 호출하여 객체를 PDF 문서에 스탬프합니다. 이 메소드는 단순성을 유지하면서 유연성을 제공합니다. 아래는 메소드의 매개변수입니다:

  • pdfFilePath: PDF 문서 경로(상대 또는 절대)를 나타내는 System.String입니다.
  • x: 왼쪽 가장자리에서 픽셀 수로 가로 위치를 나타내는 System.Int32입니다.
  • y: 아래쪽 가장자리에서 픽셀 수로 세로 위치를 나타내는 System.Int32입니다.
  • pageNumber: 페이지(1부터 시작, 첫 번째 페이지는 1)를 나타내는 System.Int32입니다.
  • password: 암호로 보호된 PDF 파일에 대한 System.String입니다(선택 사항).

StampToExistingPdfPage를 언제 사용해야 하나요?

코드 스니펫을 실행하면 중간 저장 없이 GeneratedBarcode가 PDF 문서에 직접 스탬프됩니다. 이 메소드는 다음과 같은 시나리오에 적합합니다:

  • 배송 라벨이나 배송 문서의 고유 추적 코드
  • 제조 보고서의 배치 번호
  • 법적 또는 규제 양식의 문서 관리 번호
  • 디지털 인증 또는 빠른 접근 링크를 위한 QR 코드

직접 스탬프 방법은 처리 시간을 절약하고 임시 파일을 제거합니다. For information on different barcode types, see the supported barcode formats guide.

여러 PDF 페이지에 바코드를 어떻게 스탬프하나요?

때때로 같은 바코드를 여러 페이지에 스탬프해야 합니다. 일반적인 사용 사례에는 다중 페이지 보고서의 모든 페이지에 문서 식별자를 적용하거나, 기술 문서 전체에 버전 관리 코드를 추가하거나, 기밀 자료 각 페이지에 보안 바코드를 삽입하는 것이 포함됩니다. 단일 페이지 메서드를 반복하는 대신, GeneratedBarcode 클래스의 StampToExistingPdfPages() 메서드를 사용하세요. 다음 코드 스니펫은 이 메소드를 보여줍니다.

:path=/static-assets/barcode/content-code-examples/how-to/StampBarcodeOnMultiplePdfPages.cs
using IronBarCode;
using System.Collections.Generic;

GeneratedBarcode myBarcode = BarcodeWriter.CreateBarcode("https://ironsoftware.com/csharp/barcode/", BarcodeEncoding.Code128, 200, 100);
List<int> pages = new List<int>();
pages.Add(1);
pages.Add(2);
pages.Add(3);
myBarcode.StampToExistingPdfPages("pdf_file_path.pdf", x: 200, y: 100, pages, "password");
$vbLabelText   $csharpLabel

유연성을 위해 LINQ를 사용하여 페이지 범위를 동적으로 생성하십시오:

// Stamp on all even pages from 2 to 10
var evenPages = Enumerable.Range(1, 10).Where(x => x % 2 == 0).ToList();
myBarcode.StampToExistingPdfPages("pdf_file_path.pdf", x: 200, y: 100, evenPages, "password");

// Stamp on the first and last 3 pages of a 20-page document
var selectedPages = new List<int> { 1, 2, 3, 18, 19, 20 };
myBarcode.StampToExistingPdfPages("pdf_file_path.pdf", x: 200, y: 100, selectedPages, "password");
// Stamp on all even pages from 2 to 10
var evenPages = Enumerable.Range(1, 10).Where(x => x % 2 == 0).ToList();
myBarcode.StampToExistingPdfPages("pdf_file_path.pdf", x: 200, y: 100, evenPages, "password");

// Stamp on the first and last 3 pages of a 20-page document
var selectedPages = new List<int> { 1, 2, 3, 18, 19, 20 };
myBarcode.StampToExistingPdfPages("pdf_file_path.pdf", x: 200, y: 100, selectedPages, "password");
$vbLabelText   $csharpLabel

StampToExistingPdfPages가 수용하는 매개변수는 무엇입니까?

아래는 메소드의 매개변수입니다:

  • pdfFilePath: PDF 문서 경로를 나타내는 System.String입니다.
  • x: 가로 위치를 픽셀 수로 나타내는 System.Int32입니다.
  • y: 세로 위치를 픽셀 수로 나타내는 System.Int32입니다.
  • pageNumbers: 스탬프할 페이지(1부터 시작)에 대한 IEnumerable입니다.
  • password: 암호로 보호된 PDF 파일에 대한 System.String입니다(선택 사항).

반복 대신 StampToExistingPdfPages를 사용하는 이유는 무엇입니까?

이 메소드는 수동 반복 없이 여러 페이지에 효율적인 바코드 스탬프를 제공하여 코드 가독성과 성능을 향상시킵니다. 내부 구현은 PDF 처리를 최적화하여 다음과 같은 결과를 제공합니다:

  • 더 빠른 실행: PDF가 한 번만 열리고 처리됨
  • 더 낮은 메모리 사용량: 대용량 PDF를 위한 효율적인 자원 관리
  • 더 깔끔한 코드: 수동 루프 및 오류 처리 관리 없음
  • 원자적 작업: 모든 페이지가 단일 작업으로 스탬프됨

고급 스탬프 기술

스탬프 전에 바코드 외형 사용자 정의하기

PDF에 바코드를 스탬프하기 전에, 외형을 사용자 정의하십시오. IronBarcode offers extensive customization options:

GeneratedBarcode myBarcode = BarcodeWriter.CreateBarcode("INVOICE-2024-001", BarcodeEncoding.Code128, 250, 80);

// Customize the appearance
myBarcode.AddAnnotationTextAboveBarcode("Invoice Number");
myBarcode.AddAnnotationTextBelowBarcode("Scan for digital copy");
myBarcode.SetMargins(10);
myBarcode.ChangeBarcodeForegroundColor(System.Drawing.Color.DarkBlue);

// Now stamp the customized barcode
myBarcode.StampToExistingPdfPage("invoice.pdf", x: 450, y: 700, pageNumber: 1);
GeneratedBarcode myBarcode = BarcodeWriter.CreateBarcode("INVOICE-2024-001", BarcodeEncoding.Code128, 250, 80);

// Customize the appearance
myBarcode.AddAnnotationTextAboveBarcode("Invoice Number");
myBarcode.AddAnnotationTextBelowBarcode("Scan for digital copy");
myBarcode.SetMargins(10);
myBarcode.ChangeBarcodeForegroundColor(System.Drawing.Color.DarkBlue);

// Now stamp the customized barcode
myBarcode.StampToExistingPdfPage("invoice.pdf", x: 450, y: 700, pageNumber: 1);
$vbLabelText   $csharpLabel

다른 바코드 유형과 작업하기

다양한 시나리오에는 다른 바코드 유형이 요구됩니다. QR 코드는 URL 및 대용량 데이터 세트에 적합하고, Code128은 영숫자 식별자에 적합합니다. Learn more about creating QR codes or explore other formats:

// QR Code for contact information
var qrCode = BarcodeWriter.CreateBarcode("BEGIN:VCARD\nFN:John Doe\nTEL:555-1234\nEND:VCARD", 
    BarcodeEncoding.QRCode, 150, 150);
qrCode.StampToExistingPdfPage("businesscard.pdf", x: 400, y: 50, pageNumber: 1);

// Data Matrix for product tracking
var dataMatrix = BarcodeWriter.CreateBarcode("PROD-2024-BATCH-789", 
    BarcodeEncoding.DataMatrix, 100, 100);
dataMatrix.StampToExistingPdfPage("product_sheet.pdf", x: 50, y: 750, pageNumber: 1);
// QR Code for contact information
var qrCode = BarcodeWriter.CreateBarcode("BEGIN:VCARD\nFN:John Doe\nTEL:555-1234\nEND:VCARD", 
    BarcodeEncoding.QRCode, 150, 150);
qrCode.StampToExistingPdfPage("businesscard.pdf", x: 400, y: 50, pageNumber: 1);

// Data Matrix for product tracking
var dataMatrix = BarcodeWriter.CreateBarcode("PROD-2024-BATCH-789", 
    BarcodeEncoding.DataMatrix, 100, 100);
dataMatrix.StampToExistingPdfPage("product_sheet.pdf", x: 50, y: 750, pageNumber: 1);
$vbLabelText   $csharpLabel

오류 처리 및 모범 사례

PDF 스탬핑 작업에서 적절한 오류 처리를 구현하십시오:

try
{
    GeneratedBarcode myBarcode = BarcodeWriter.CreateBarcode("DOCUMENT-ID-12345", 
        BarcodeEncoding.Code128, 200, 60);

    // Verify the PDF exists before attempting to stamp
    if (File.Exists("target.pdf"))
    {
        myBarcode.StampToExistingPdfPage("target.pdf", x: 100, y: 100, pageNumber: 1);
        Console.WriteLine("Barcode stamped successfully!");
    }
    else
    {
        Console.WriteLine("PDF file not found!");
    }
}
catch (Exception ex)
{
    Console.WriteLine($"Error stamping barcode: {ex.Message}");
    // Log the error or handle it appropriately
}
try
{
    GeneratedBarcode myBarcode = BarcodeWriter.CreateBarcode("DOCUMENT-ID-12345", 
        BarcodeEncoding.Code128, 200, 60);

    // Verify the PDF exists before attempting to stamp
    if (File.Exists("target.pdf"))
    {
        myBarcode.StampToExistingPdfPage("target.pdf", x: 100, y: 100, pageNumber: 1);
        Console.WriteLine("Barcode stamped successfully!");
    }
    else
    {
        Console.WriteLine("PDF file not found!");
    }
}
catch (Exception ex)
{
    Console.WriteLine($"Error stamping barcode: {ex.Message}");
    // Log the error or handle it appropriately
}
$vbLabelText   $csharpLabel

성능 고려 사항

대용량 PDF 또는 여러 스탬핑 작업을 수행할 때 다음 팁을 고려하십시오:

  1. 일괄 작업: StampToExistingPdfPage()를 반복하는 대신 StampToExistingPdfPages()를 사용하세요
  2. 바코드 캐싱: 한번 생성하여 GeneratedBarcode 객체를 재사용하세요
  3. 좌표 계산: 일관된 위치 좌표를 미리 계산하십시오
  4. 메모리 관리: 매우 큰 PDF를 배치로 처리하십시오

For advanced scenarios involving reading barcodes from PDFs after stamping, see our guide on reading barcodes from PDF documents.

다른 IronBarcode 기능과의 통합

PDF 스탬핑 기능은 다른 IronBarcode 기능과 원활하게 작동합니다. Combine it with asynchronous processing for better web application performance:

// Asynchronous PDF stamping
public async Task StampBarcodeAsync(string pdfPath, string barcodeData)
{
    await Task.Run(() =>
    {
        var barcode = BarcodeWriter.CreateBarcode(barcodeData, BarcodeEncoding.QRCode, 200, 200);
        barcode.StampToExistingPdfPage(pdfPath, x: 100, y: 100, pageNumber: 1);
    });
}
// Asynchronous PDF stamping
public async Task StampBarcodeAsync(string pdfPath, string barcodeData)
{
    await Task.Run(() =>
    {
        var barcode = BarcodeWriter.CreateBarcode(barcodeData, BarcodeEncoding.QRCode, 200, 200);
        barcode.StampToExistingPdfPage(pdfPath, x: 100, y: 100, pageNumber: 1);
    });
}
$vbLabelText   $csharpLabel

Additionally, leverage IronBarcode's image correction features when working with scanned PDFs that might need enhancement before or after barcode stamping.

일반적인 문제 해결

PDF에 바코드를 스탬핑하는 동안 문제가 발생하면 다음 솔루션을 참조하십시오:

  1. 좌표 문제: PDF 좌표는 왼쪽 위가 아니라 왼쪽 아래에서 시작합니다
  2. 암호 보호된 PDF: 암호화된 PDF에 대한 올바른 암호 매개변수를 확인하십시오
  3. Large File Sizes: For optimization and handling tips, see our troubleshooting guide
  4. Font or Encoding Issues: For special characters or Unicode, check our writing Unicode barcodes guide

이러한 지침을 따르고 IronBarcode의 PDF 스탬핑 기능을 활용하면 기존 PDF 문서에 바코드를 효율적으로 추가하면서 높은 성능과 코드 품질을 유지할 수 있습니다.

자주 묻는 질문

C#에서 기존 PDF 문서에 바코드를 추가하는 방법은 무엇인가요?

IronBarcode의 CreateBarcode 메서드를 사용하여 바코드를 생성한 다음, StampToExistingPdfPage 메서드를 적용하여 PDF에 바코드를 삽입합니다. PDF 파일 경로, 위치 좌표(x, y) 및 바코드가 나타날 페이지 번호만 지정하면 됩니다.

StampToExistingPdfPage 메서드에 필요한 매개변수는 무엇입니까?

IronBarcode의 StampToExistingPdfPage 메서드는 다음 매개변수를 필요로 합니다: pdfFilePath(PDF 파일 위치를 나타내는 문자열), x 및 y 좌표(픽셀 단위의 위치를 나타내는 정수), pageNumber(1부터 시작하는 정수), 그리고 보호된 PDF 파일의 경우 선택적으로 암호 매개변수를 사용할 수 있습니다.

PDF 파일의 여러 페이지에 동일한 바코드를 찍을 수 있나요?

네, IronBarcode는 StampToExistingPdfPages 메서드(복수형인 'Pages'에 유의하세요)를 제공하여 생성된 단일 바코드를 PDF 문서의 여러 페이지에 걸쳐 찍을 수 있도록 합니다.

PDF 파일에서 바코드를 배치하는 데 사용되는 좌표계는 무엇입니까?

IronBarcode는 StampToExistingPdfPage 메서드를 사용할 때 픽셀 기반 좌표계를 사용하며, x 좌표는 페이지의 왼쪽 가장자리에서, y 좌표는 페이지의 아래쪽 가장자리에서 측정됩니다.

기존 PDF 파일에 바코드를 삽입하는 일반적인 사용 사례는 무엇인가요?

IronBarcode의 PDF 스탬핑 기능은 일반적으로 배송 라벨에 고유 추적 코드를 추가하거나, 제조 보고서에 배치 번호를 추가하거나, 법률 양식에 문서 관리 번호를 추가하거나, 디지털 인증 또는 빠른 액세스 링크를 위한 QR 코드를 추가하는 데 사용됩니다.

PDF에 바코드를 삽입하려면 중간 파일을 저장해야 하나요?

아니요, IronBarcode의 StampToExistingPdfPage 메서드는 임시 파일을 생성하지 않고 바코드를 PDF 문서에 직접 찍기 때문에 처리 시간과 저장 공간을 절약할 수 있습니다.

비밀번호로 보호된 PDF 문서에 바코드를 찍을 수 있나요?

네, IronBarcode는 암호로 보호된 PDF에 바코드를 찍는 기능을 지원합니다. StampToExistingPdfPage 메서드에 PDF 암호를 선택적 매개변수로 제공하기만 하면 됩니다.

하릴 하시미 빈 오마르
소프트웨어 엔지니어
모든 훌륭한 엔지니어처럼, 하이릴은 열정적인 학습자입니다. 그는 C#, Python, Java에 대한 지식을 갈고닦아 Iron Software의 팀원들에게 가치를 더하고 있습니다. 하이릴은 말레이시아의 Universiti Teknologi MARA에서 화학 및 공정 공학 학사 학위를 취득한 후 Iron Software 팀에 합류했습니다.
시작할 준비 되셨나요?
Nuget 다운로드 2,108,094 | 버전: 2026.3 방금 출시되었습니다
Still Scrolling Icon

아직도 스크롤하고 계신가요?

빠른 증거를 원하시나요? PM > Install-Package BarCode
샘플을 실행하세요 실이 바코드로 변하는 모습을 지켜보세요.