Home > Backend Development > C++ > How to Eliminate Vertical Whitespace When Merging PDF Files in C#?

How to Eliminate Vertical Whitespace When Merging PDF Files in C#?

Susan Sarandon
Release: 2025-01-05 00:00:40
Original
782 people have browsed it

How to Eliminate Vertical Whitespace When Merging PDF Files in C#?

How to Remove Whitespace on Merge

This code efficiently merges three PDF byte arrays. However, the resulting document exhibits vertical whitespace on each page, making it appear as separate pages. Here's how to eliminate this whitespace:

C# Implementation (Updated)

public class PdfVeryDenseMergeTool
{
    private Rectangle PageSize;
    private float TopMargin;
    private float BottomMargin;
    private float Gap;
    private Document Document = null;
    private PdfWriter Writer = null;
    private float YPosition = 0;

    public PdfVeryDenseMergeTool(Rectangle size, float top, float bottom, float gap)
    {
        this.PageSize = size;
        this.TopMargin = top;
        this.BottomMargin = bottom;
        this.Gap = gap;
    } // PdfVeryDenseMergeTool

    public void Merge(MemoryStream outputStream, List<PdfReader> inputs)
    {
        try
        {
            this.OpenDocument(outputStream);

            foreach (PdfReader reader in inputs)
            {
                this.Merge(reader);
            } // foreach of the PDF files to merge
        }
        finally
        {
            this.CloseDocument();
        } // try-catch-finally
    } // Merge

    public void OpenDocument(MemoryStream outputStream)
    {
        this.Document = new Document(PageSize, 36, 36, this.TopMargin, this.BottomMargin);
        this.Writer = PdfWriter.GetInstance(Document, outputStream);

        this.Document.Open();
        this.NewPage();
    } // OpenDocument

    public void CloseDocument()
    {
        try
        {
            this.Document.Close();
        }
        finally
        {
            this.Document = null;
            this.Writer = null;
            this.YPosition = 0;
        } // try-finally
    } // CloseDocument

    public void NewPage()
    {
        this.Document.NewPage();
        this.YPosition = PageSize.GetTop(this.TopMargin);
    } // Merge

    public void Merge(PdfReader reader)
    {
        PdfReaderContentParser parser = new PdfReaderContentParser(reader);

        for (int pageIndex = 1; pageIndex <= reader.NumberOfPages; pageIndex++)
        {
            this.Merge(reader, parser, pageIndex);
        } // foreach of the pages of the current PDF
    } // Merge

    public void Merge(PdfReader reader, PdfReaderContentParser parser, int pageIndex)
    {
        PdfImportedPage importedPage = Writer.GetImportedPage(reader, pageIndex);
        PdfContentByte directContent = Writer.DirectContent;

        PageVerticalAnalyzer finder = parser.ProcessContent(pageIndex, new PageVerticalAnalyzer());

        if (finder.VerticalFlips.Count < 2)
            return;

        Rectangle pageSizeToImport = reader.GetPageSize(pageIndex);

        int startFlip = finder.VerticalFlips.Count - 1;
        bool first = true;

        while (startFlip > 0)
        {
            if (!first)
                this.NewPage();

            float freeSpace = this.YPosition - PageSize.GetBottom(BottomMargin);
            int endFlip = startFlip + 1;

            while ((endFlip > 1) &amp;&amp; (finder.VerticalFlips[startFlip] - finder.VerticalFlips[endFlip - 2] < freeSpace))
                endFlip -= 2;

            if (endFlip < startFlip)
            {
                float height = finder.VerticalFlips[startFlip] - finder.VerticalFlips[endFlip];

                directContent.SaveState();
                directContent.Rectangle(0, this.YPosition - height, pageSizeToImport.Width, height);
                directContent.Clip();
                directContent.NewPath();

                this.Writer.DirectContent.AddTemplate(importedPage, 0, this.YPosition - (finder.VerticalFlips[startFlip] - pageSizeToImport.Bottom));

                directContent.RestoreState();
                this.YPosition -= height + this.Gap;
                startFlip = endFlip - 1;
            }
            else if (!first)
            {
                throw new ArgumentException(string.Format("Page {0} content too large", pageIndex));
            } // if

            first = false;
        } // while
    } // Merge
} // PdfVeryDenseMergeTool
Copy after login

PageVerticalAnalyzer Class:

public class PageVerticalAnalyzer : IRenderListener
{
    public PageVerticalAnalyzer() { }

    public List<float> VerticalFlips = new List<float>();

    public void AddVerticalUseSection(float from, float to)
    {
        if (to < from)
        {
            float temp = to;
            to = from;
            from = temp;
        }

        int i = 0;
        int j = 0;

        for (i = 0; i < VerticalFlips.Count; i++)
        {
            float flip = VerticalFlips[i];
            if (flip < from)
                continue;

            for (j = i; j < VerticalFlips.Count; j++)
            {
                flip = VerticalFlips[j];
                if (flip < to)
                    continue;
                break;
            }
            break;
        } // foreach of the vertical flips

        bool fromOutsideInterval = i % 2 == 0;
        bool toOutsideInterval = j % 2 == 0;

        while (j-- > i)
            VerticalFlips.RemoveAt(j); // This was the problem line with just .Remove(j)
        if (toOutsideInterval)
Copy after login

The above is the detailed content of How to Eliminate Vertical Whitespace When Merging PDF Files in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template