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

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

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

C#에서 IronBarcode의 CreateBarcode 메서드를 사용하여 기존 PDF 문서에 BARCODE를 찍을 수 있습니다. 단일 페이지의 경우 StampToExistingPdfPage를, 여러 페이지의 경우 StampToExistingPdfPages를 사용하여 좌표와 페이지 번호를 지정합니다.

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

이 예제는 IronBarcode의 CreateBarcode를 사용하여 BARCODE를 생성하고 기존 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

StampToExistingPdfPage StampToExistingPdfPages

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

IronBarcode는 BarCode를 PDF로 내보내는 것 외에도, 기존 PDF 문서에 GeneratedBarcode를 직접 삽입할 수 있는 기능을 제공합니다. 이 기능은 기존 보고서, 송장, 양식에 추적 코드, 인벤토리 라벨, 문서 식별자를 추가할 때 유용합니다. 다음 코드 스니펫은 이 작업을 보여줍니다.

: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");
Imports IronBarCode

Private myBarcode As GeneratedBarcode = 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에 필요한 매개변수는 무엇입니까?

StampToExistingPdfPage() GeneratedBarcode

이 코드 스니펫은 StampToExistingPdfPage 객체를 사용하여 StampSettings 메서드를 호출함으로써 해당 객체를 PDF 문서에 삽입합니다. 이 메소드는 단순성을 유지하면서 유연성을 제공합니다. 아래는 메소드의 매개변수입니다:

  • pdfFilePath: PDF 문서 경로(상대 경로 또는 절대 경로)를 나타내는 System.String입니다.
  • x: 왼쪽 가장자리로부터의 수평 위치를 픽셀 단위로 나타내는 System.Int32 값입니다.
  • y: 하단 가장자리로부터의 수직 위치를 픽셀 단위로 나타내는 System.Int32 값입니다.
  • pageNumber: 페이지를 나타내는 System.Int32 값(1부터 시작하는 인덱스, 첫 페이지는 1).
  • password: 암호로 보호된 PDF용 System.String(선택 사항).

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

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

StampToExistingPdfPages() GeneratedBarcode

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

직접 스탬프 방법은 처리 시간을 절약하고 임시 파일을 제거합니다. 다른 바코드 유형에 대한 정보는 지원되는 바코드 형식 가이드를 참조하십시오.

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

때때로 같은 바코드를 여러 페이지에 스탬프해야 합니다. 일반적인 사용 사례에는 다중 페이지 보고서의 모든 페이지에 문서 식별자를 적용하거나, 기술 문서 전체에 버전 관리 코드를 추가하거나, 기밀 자료 각 페이지에 보안 바코드를 삽입하는 것이 포함됩니다. 단일 페이지 메서드를 반복하는 대신, BarcodeStamper 클래스의 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");
Imports IronBarCode
Imports System.Collections.Generic

Private myBarcode As GeneratedBarcode = BarcodeWriter.CreateBarcode("https://ironsoftware.com/csharp/barcode/", BarcodeEncoding.Code128, 200, 100)
Private pages As New List(Of Integer)()
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");
Imports System.Linq

' Stamp on all even pages from 2 to 10
Dim evenPages = Enumerable.Range(1, 10).Where(Function(x) x Mod 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
Dim selectedPages = New List(Of Integer) From {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: 스탬프를 찍을 페이지의 IEnumerable</system.int32>(1부터 인덱싱됨).
  • password: 암호로 보호된 PDF용 System.String(선택 사항).

StampToExistingPdfPages() StampToExistingPdfPage() GeneratedBarcode

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

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

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

고급 스탬프 기술

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

PDF에 바코드를 스탬프하기 전에, 외형을 사용자 정의하십시오. IronBarcode는 광범위한 사용자 정의 옵션을 제공합니다:

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

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

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

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

// Now stamp the customized barcode
myBarcode.StampToExistingPdfPage("invoice.pdf", x: 450, y: 700, pageNumber: 1);
Imports System.Drawing

Dim myBarcode As GeneratedBarcode = 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(Color.DarkBlue)

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

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

다양한 시나리오에는 다른 바코드 유형이 요구됩니다. QR 코드는 URL 및 대용량 데이터 세트에 적합하고, Code128은 영숫자 식별자에 적합합니다. QR 코드 생성 방법에 대해 더 알아보거나 다른 형식을 탐색하십시오:

// 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);
' QR Code for contact information
Dim qrCode = BarcodeWriter.CreateBarcode("BEGIN:VCARD" & vbLf & "FN:John Doe" & vbLf & "TEL:555-1234" & vbLf & "END:VCARD", 
    BarcodeEncoding.QRCode, 150, 150)
qrCode.StampToExistingPdfPage("businesscard.pdf", x:=400, y:=50, pageNumber:=1)

' Data Matrix for product tracking
Dim 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.Co/de128, 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.Co/de128, 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
}
Imports System
Imports System.IO

Try
    Dim myBarcode As GeneratedBarcode = BarcodeWriter.CreateBarcode("DOCUMENT-ID-12345", BarcodeEncoding.Code128, 200, 60)

    ' Verify the PDF exists before attempting to stamp
    If File.Exists("target.pdf") Then
        myBarcode.StampToExistingPdfPage("target.pdf", x:=100, y:=100, pageNumber:=1)
        Console.WriteLine("Barcode stamped successfully!")
    Else
        Console.WriteLine("PDF file not found!")
    End If
Catch ex As Exception
    Console.WriteLine($"Error stamping barcode: {ex.Message}")
    ' Log the error or handle it appropriately
End Try
$vbLabelText   $csharpLabel

성능 고려 사항

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

  1. 일괄 처리: StampToExistingPdfPages을 반복문 StampToExistingPdfPage 대신 사용하십시오.
  2. BarCode 캐싱: GeneratedBarcode 객체를 한 번 생성하여 재사용
  3. 좌표 계산: 일관된 위치 좌표를 미리 계산하십시오
  4. 메모리 관리: 매우 큰 PDF를 배치로 처리하십시오

스탬핑 후 PDF에서 바코드를 읽는 고급 시나리오의 경우, 우리 가이드에서 PDF 문서에서 바코드 읽기를 참조하십시오.

다른 IronBarcode 기능과의 통합

PDF 스탬핑 기능은 다른 IronBarcode 기능과 원활하게 작동합니다. 비동기 처리와 결합하여 웹 애플리케이션 성능을 향상시키십시오:

// 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);
    });
}
Imports System.Threading.Tasks

' Asynchronous PDF stamping
Public Async Function StampBarcodeAsync(pdfPath As String, barcodeData As String) As Task
    Await Task.Run(Sub()
                       Dim barcode = BarcodeWriter.CreateBarcode(barcodeData, BarcodeEncoding.QRCode, 200, 200)
                       barcode.StampToExistingPdfPage(pdfPath, x:=100, y:=100, pageNumber:=1)
                   End Sub)
End Function
$vbLabelText   $csharpLabel

또한 스캔된 PDF에서 바코드 스탬핑 전후에 개선이 필요할 수 있는 경우 IronBarcode의 이미지 수정 기능을 활용하십시오.

일반적인 문제 해결

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

  1. 좌표 문제: PDF 좌표는 왼쪽 위가 아니라 왼쪽 아래에서 시작합니다
  2. 암호 보호된 PDF: 암호화된 PDF에 대한 올바른 암호 매개변수를 확인하십시오
  3. 대용량 파일 크기: 최적화 및 처리 팁은 우리의 트러블슈팅 가이드를 참조하십시오
  4. 폰트 또는 인코딩 문제: 특수 문자 또는 유니코드의 경우 우리의 유니코드 바코드 작성 가이드를 확인하십시오

이러한 지침을 따르고 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 암호를 선택적 매개변수로 제공하기만 하면 됩니다.

IronBarcode가 비즈니스 프로세스 효율성을 어떻게 향상시킬 수 있나요?

IronBarcode는 빠르고 정확한 바코드 생성 및 읽기를 가능하게 하여 수동 데이터 입력 오류를 줄이고, 재고 및 자산 추적을 향상시킴으로써 비즈니스 프로세스 효율성을 향상시킵니다.

IronBarcode를 프로젝트에 구현하려면 어떤 프로그래밍 기술이 필요하나요?

C# 프로그래밍의 기본 지식만 있으면 IronBarcode를 프로젝트에 구현하기에 충분합니다. IronBarcode는 개발자를 안내할 수 있는 간단한 메서드와 포괄적인 문서를 제공합니다.

IronBarcode는 소규모 프로젝트와 대규모 Enterprise 응용 프로그램 모두에 적합합니까?

IronBarcode는 확장 가능하고 다재다능하게 설계되어 소규모 프로젝트뿐만 아니라 견고한 바코드 솔루션이 필요한 대규모 Enterprise 응용 프로그램에 적합합니다.

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

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

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