PDF 문서 비교

모든 비교 도구는 Aspose.PDF.Drawing 라이브러리에서 사용할 수 있습니다.

PDF 문서 비교 방법

PDF 문서 작업 시 두 문서의 내용을 비교하여 차이를 식별해야 할 때가 있습니다. Aspose.PDF for .NET 라이브러리는 이를 위한 강력한 도구 세트를 제공합니다. 이 기사에서는 간단한 코드 스니펫을 사용하여 PDF 문서를 비교하는 방법을 살펴보겠습니다.

Aspose.PDF의 비교 기능을 사용하면 두 PDF 문서를 페이지별로 비교할 수 있습니다. 특정 페이지 또는 전체 문서를 비교하도록 선택할 수 있습니다. 결과 비교 문서는 차이를 강조 표시하여 두 파일 간의 변경 사항을 쉽게 식별할 수 있도록 합니다.

다음은 Aspose.PDF for .NET 라이브러리를 사용하여 PDF 문서를 비교하는 가능한 방법 목록입니다:

  1. 특정 페이지 비교 - 두 PDF 문서의 첫 페이지를 비교합니다.

  2. 전체 문서 비교 - 두 PDF 문서의 전체 내용을 비교합니다.

  3. 그래픽적으로 PDF 문서 비교:

  • GetDifference 메서드를 사용하여 PDF 비교 - 변경 사항이 표시된 개별 이미지.

  • CompareDocumentsToPdf 메서드를 사용하여 PDF 비교 - 변경 사항이 표시된 이미지가 포함된 PDF 문서.

특정 페이지 비교

첫 번째 코드 스니펫은 두 PDF 문서의 첫 페이지를 비교하는 방법을 보여줍니다.

  1. 문서 초기화. 코드는 각 문서의 파일 경로(documentPath1 및 documentPath2)를 사용하여 두 PDF 문서를 초기화하는 것으로 시작합니다. 경로는 현재 빈 문자열로 지정되어 있지만, 실제로는 이를 실제 파일 경로로 교체해야 합니다.

  2. 비교 프로세스.

  • 페이지 선택 - 비교는 각 문서의 첫 페이지(‘Pages[1]’)로 제한됩니다.
  • 비교 옵션:

‘AdditionalChangeMarks = true’ - 이 옵션은 추가 변경 마커가 표시되도록 합니다. 이러한 마커는 현재 비교 중인 페이지에 없더라도 다른 페이지에 있을 수 있는 차이를 강조 표시합니다.

‘ComparisonMode = ComparisonMode.IgnoreSpaces’ - 이 모드는 비교기가 텍스트의 공백을 무시하고 단어 내의 변경 사항에만 집중하도록 지시합니다.

  1. 두 페이지 간의 차이를 강조 표시하는 결과 비교 문서는 ‘resultPdfPath’에 지정된 파일 경로에 저장됩니다.
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ComparingSpecificPages()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_DocumentCompare();

    // Open PDF documents
    using (var document1 = new Aspose.Pdf.Document(dataDir + "ComparingSpecificPages1.pdf"))
    {
        using (var document2 = new Aspose.Pdf.Document(dataDir + "ComparingSpecificPages2.pdf"))
        {
            // Compare
            Aspose.Pdf.Comparison.SideBySidePdfComparer.Compare(document1.Pages[1], document2.Pages[1], dataDir + "ComparingSpecificPages_out.pdf", new Aspose.Pdf.Comparison.SideBySideComparisonOptions
            {
                AdditionalChangeMarks = true,
                ComparisonMode = Aspose.Pdf.Comparison.ComparisonMode.IgnoreSpaces,
                DeleteColor = Color.DarkGray,
                InsertColor = Color.LightYellow
            });
        }
    }
}

전체 문서 비교

두 번째 코드 스니펫은 두 PDF 문서의 전체 내용을 비교하는 범위를 확장합니다.

// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ComparingEntireDocuments()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_DocumentCompare();

    // Open PDF documents
    using (var document1 = new Aspose.Pdf.Document(dataDir + "ComparingEntireDocuments1.pdf"))
    {
        using (var document2 = new Aspose.Pdf.Document(dataDir + "ComparingEntireDocuments2.pdf"))
        {
            // Compare
            Aspose.Pdf.Comparison.SideBySidePdfComparer.Compare(
                document1,
                document2,
                dataDir + "ComparingEntireDocuments_out.pdf",
                new Aspose.Pdf.Comparison.SideBySideComparisonOptions
                {
                    AdditionalChangeMarks = true,
                    ComparisonMode = Aspose.Pdf.Comparison.ComparisonMode.IgnoreSpaces,
                    DeleteColor = Color.DarkGray,
                    InsertColor = Color.LightYellow
                });
        }
    }
}

이 스니펫에서 생성된 비교 결과는 Adobe Acrobat과 같은 뷰어에서 열 수 있는 PDF 문서입니다. Adobe Acrobat에서 두 페이지 보기 모드를 사용하면 변경 사항을 나란히 볼 수 있습니다:

  • 삭제 - 왼쪽 페이지에 기록됩니다.
  • 삽입 - 오른쪽 페이지에 기록됩니다.

‘AdditionalChangeMarks’를 ’true’로 설정하면 현재 보고 있는 페이지에 변경 사항이 없더라도 다른 페이지에서 발생할 수 있는 변경 사항에 대한 마커도 볼 수 있습니다.

Aspose.PDF for .NET은 특정 페이지 또는 전체 문서를 비교해야 할 때 강력한 PDF 문서 비교 도구를 제공합니다. ‘AdditionalChangeMarks’ 및 다양한 ‘ComparisonMode 설정’과 같은 옵션을 사용하여 비교 프로세스를 특정 요구 사항에 맞게 조정할 수 있습니다. 결과 문서는 변경 사항을 명확하게 나란히 보여주어 수정 사항을 추적하고 문서의 정확성을 보장하는 데 도움이 됩니다.

GraphicalPdfComparer를 사용한 PDF 문서 비교

문서에서 협업할 때, 특히 전문 환경에서는 동일한 파일의 여러 버전을 갖게 되는 경우가 많습니다.

GraphicalPdfComparer 클래스를 사용하여 PDF 문서와 페이지를 비교할 수 있습니다. 이 클래스는 페이지의 그래픽 콘텐츠에서 변경 사항을 비교하는 데 적합합니다.

Aspose.PDF for .NET을 사용하면 문서와 페이지를 비교하고 비교 결과를 PDF 문서 또는 이미지 파일로 출력할 수 있습니다.

다음 클래스 속성을 설정할 수 있습니다:

  • 해상도 - 출력 이미지 및 비교 중 생성된 이미지의 DPI 단위 해상도.
  • 색상 - 변경 마커의 색상.
  • 임계값 - 백분율로 표시된 변경 임계값. 기본값은 0입니다. 0이 아닌 값을 설정하면 중요하지 않은 그래픽 변경 사항을 무시할 수 있습니다.

이 클래스에는 추가 처리를 위해 적합한 형태로 페이지 이미지 차이를 가져오는 메서드가 있습니다: ImagesDifference GetDifference(Page page1, Page page2).

이 메서드는 비교되는 첫 번째 페이지의 이미지와 차이 배열을 포함하는 ImagesDifference 클래스의 객체를 반환합니다. 차이 배열과 원본 이미지는 RGB24bpp 픽셀 형식을 가집니다.

ImagesDifference를 사용하면 다른 이미지를 생성하고 차이 배열을 원본 이미지에 추가하여 비교되는 두 번째 페이지의 이미지를 얻을 수 있습니다. 이를 위해 ImagesDifference.GetDestinationImage 및 ImagesDifference.DifferenceToImage 메서드를 사용합니다.

GetDifference 메서드를 사용한 PDF 비교

제공된 코드는 두 PDF 문서를 비교하고 그들 간의 차이를 시각적으로 표현하는 GetDifference 메서드를 정의합니다.

이 메서드는 두 PDF 파일의 첫 페이지를 비교하고 두 개의 PNG 이미지를 생성합니다:

  • 하나의 이미지는(diffPngFilePath) 페이지 간의 차이를 빨간색으로 강조 표시합니다.
  • 다른 이미지는(destPngFilePath) 두 번째 PDF 페이지의 시각적 표현입니다.

이 과정은 문서의 두 버전 간의 변경 사항이나 차이를 시각적으로 비교하는 데 유용할 수 있습니다.

// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ComparePDFWithGetDifferenceMethod()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_DocumentCompare();

    // Open PDF documents
    using (var document1 = new Aspose.Pdf.Document(dataDir + "ComparePDFWithGetDifferenceMethod1.pdf"))
    {
        using (var document2 = new Aspose.Pdf.Document(dataDir + "ComparePDFWithGetDifferenceMethod2.pdf"))
        {
            // Create comparer 
            var comparer = new Aspose.Pdf.Comparison.GraphicalPdfComparer();
            // Compare
            using (var imagesDifference = comparer.GetDifference(document1.Pages[1], document2.Pages[1]))
            {
                using (var diffImg = imagesDifference.DifferenceToImage(Aspose.Pdf.Color.Red, Aspose.Pdf.Color.White))
                {
                    diffImg.Save(dataDir + "ComparePDFWithGetDifferenceMethodDiffPngFilePath_out.png");
                }
                using (var destImg = imagesDifference.GetDestinationImage())
                {
                    destImg.Save(dataDir + "ComparePDFWithGetDifferenceMethodDestPngFilePath_out.png");
                }
            }
        }
    }
}

CompareDocumentsToPdf 메서드를 사용한 PDF 비교

제공된 코드 스니펫은 두 문서를 비교하고 비교 결과의 PDF 보고서를 생성하는 CompareDocumentsToPdf 메서드를 사용합니다.

// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ComparePDFWithCompareDocumentsToPdfMethod()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_DocumentCompare();

    // Open PDF documents
    using (var document1 = new Aspose.Pdf.Document(dataDir + "ComparePDFWithCompareDocumentsToPdfMethod1.pdf"))
    {
        using (var document2 = new Aspose.Pdf.Document(dataDir + "ComparePDFWithCompareDocumentsToPdfMethod2.pdf"))
        {
            // Create comparer
            var comparer = new Aspose.Pdf.Comparison.GraphicalPdfComparer()
            {
                Threshold = 3.0,
                Color = Aspose.Pdf.Color.Blue,
                Resolution = new Aspose.Pdf.Devices.Resolution(300)
            };
            // Compare
            comparer.CompareDocumentsToPdf(document1, document2, dataDir + "compareDocumentsToPdf_out.pdf");
        }
    }
}

문서 비교를 위한 범용 메서드

TextPdfComparer 클래스를 사용하여 문서와 개별 페이지를 비교할 수 있습니다. 이 클래스는 페이지별로 또는 단일 연속 콘텐츠 스트림(페이지 분리 없이)으로 문서를 비교할 수 있습니다. 비교 메서드는 IStringOutputGenerator 또는 IFileOutputGenerator 인터페이스를 구현하는 모든 클래스에 전달할 수 있는 차이 배열을 반환하여 형식화된 비교 출력을 생성합니다. 출력은 HTML, Markdown, PDF, 및 JSON 형식으로 지원됩니다. 또한 ComparisonStatistics 클래스를 사용하여 수행된 비교 작업에 대한 통계를 얻을 수 있습니다.

메서드 설명 매개변수 반환 값
CompareDocumentsPageByPage(Document document1, Document document2, ComparisonOptions options) 두 PDF 문서를 페이지별로 비교합니다. * document1 – 첫 번째 문서.
* document2 – 두 번째 문서.
* options – 비교 옵션(아래 참조).
List<List<DiffOperation>> – 각 페이지의 차이 목록.
CompareDocumentsPageByPage(Document document1, Document document2, ComparisonOptions options, string resultPdfDocumentPath) 위와 동일하지만 비교 결과를 PDF 파일에 저장합니다. 위와 동일한 매개변수 + resultPdfDocumentPath – 출력 파일의 경로. List<List<DiffOperation>> – 차이 목록.
CompareFlatDocuments(Document document1, Document document2, ComparisonOptions options) 두 PDF 문서를 단일 연속 텍스트로 비교합니다(모든 페이지 병합). CompareDocumentsPageByPage와 동일한 매개변수. List<DiffOperation> – 모든 차이 목록.
CompareFlatDocuments(Document document1, Document document2, ComparisonOptions options, string resultPdfDocumentPath) 결과가 PDF 파일로 저장되는 평면 문서 비교입니다. CompareFlatDocuments와 동일한 매개변수 + resultPdfDocumentPath. List<DiffOperation> – 차이 목록.
ComparePages(Page page1, Page page2, ComparisonOptions options) 두 개별 페이지를 비교합니다. * page1 – 첫 번째 페이지.
* page2 – 두 번째 페이지.
* options – 비교 옵션.
List<DiffOperation> – 페이지 차이 목록.
CreateComparisonStatistics(List<DiffOperation> diffs) 단일 페이지에 대한 작업 목록의 비교 통계를 생성합니다. diffsDiffOperation 목록. TextItemComparisonStatistics (아래 참조).
CreateComparisonStatistics(List<List<DiffOperation>> diffs) 페이지 간의 작업 목록에 대한 비교 통계를 생성합니다(문서 수준). diffsDiffOperation 목록의 목록. DocumentComparisonStatistics (아래 참조).
AssemblySourcePageText(List<DiffOperation> diffs) 원본(변경 전) 페이지 텍스트를 재구성합니다. diffs – 작업 목록. string – 원본 텍스트.
AssemblyDestinationPageText(List<DiffOperation> diffs) 수정된(변경 후) 페이지 텍스트를 재구성합니다. diffs – 작업 목록. string – 수정된 텍스트.

관련 공개 클래스

ComparisonOptions

비교 프로세스에 영향을 미치는 매개변수:

속성 유형 설명
ExtractionArea Rectangle 텍스트가 추출될 영역. ExcludeTables, ExcludeAreas1/2와 호환되지 않습니다.
ExcludeTables bool 비교에서 테이블을 제외합니다. ExtractionArea와 호환되지 않습니다.
ExcludeAreas1 Rectangle[] 첫 번째 문서에 대해 제외할 영역의 배열입니다.
ExcludeAreas2 Rectangle[] 두 번째 문서에 대해 제외할 영역의 배열입니다.
EditOperationsOrder EditOperationsOrder (enum) 삽입/삭제 작업을 적용하는 순서(기본값은 DeleteFirst).

DiffOperation

단일 차이 작업을 나타냅니다. 포함된 내용:

속성 유형 설명
Operation Operation (enum) 작업 유형(Equal, Delete, Insert).
Text string 작업과 관련된 텍스트입니다.

ComparisonStatistics

클래스 설명
TextItemComparisonStatistics 개별 텍스트(페이지)에 대한 통계. 총 문자 수, 삽입 및 삭제 수, 해당 작업을 포함합니다.
DocumentComparisonStatistics (inherits from TextItemComparisonStatistics) 전체 문서에 대한 확장된 통계, PagesStatistics 목록(페이지별 통계)을 포함합니다.

사용 예제