-1

I want to merge many pdf to a single one with Pdftk.

How can i make it so that whenever a pdf has an odd number of pages, a blank page is added?

I need this function for a cmd tool which i need to write in c#.

The PDF should be printed double-sided.

using System.Diagnostics;
using System.IO;
using MergePdf.Properties;
using System.Linq;
using System.Collections;
using System.Runtime.InteropServices;
using System.Collections.Generic;

namespace System.Configuration
{
    class Program
    {
          static void Main(string[] args)
    {
        Console.Title = "MergePDF";

        // Folder from which the PDF will be pulled
        string altDirIn = Settings.Default.AlternativeInputDir;

        // Folder in which the merged PDF will be placed
        string altDirOut = Settings.Default.AlternativeOutputDir;

        // sort the files by the first name before the "_"
        var rchg = new DirectoryInfo(altDirIn);
        var files1 = rchg.EnumerateFiles("*.pdf").OrderBy(fi => Convert.ToInt32(fi.Name.Split('_')[0]));
        var cmd1 = $"{string.Join(" ", files1.Select(fi => fi.FullName))} cat output {altDirOut}";



        var evn = new DirectoryInfo(altDirIn);
        var files2 = evn.EnumerateFiles("*.pdf").OrderBy(fi => Convert.ToInt32(fi.Name.Split('_')[0]));
        var cmd2 = $"{string.Join(" ", files2.Select(fi => fi.FullName))} cat output {altDirOut}";

        Process p = new Process();
        p.StartInfo.WorkingDirectory = Environment.CurrentDirectory;
        p.StartInfo.FileName = "pdftk.exe";
        p.StartInfo.Arguments = cmd1;
        p.StartInfo.Arguments = cmd2;
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.RedirectStandardError = true;
        p.Start();

        Console.WriteLine(p.StandardError.ReadToEnd());

        Console.WriteLine("Bitte drücken Sie eine beliebige Taste, um das Programm zu beenden...");

        Console.ReadKey();

        p.WaitForExit();
    }
}
}

When I do it this way, I have the problem that if, for example, a pdf has an odd number of pages, then on the back of the last page of the first pdf is the first page of the next pdf.

How can I proceed so that each pdf gets an even number of pages?

best regards and thanks in advance

aljoscha
  • 11
  • 5

1 Answers1

0

If you can shell out to pdftk, you can shell out to cpdf and run:

cpdf -pad-multiple x in.pdf -o out.pdf

Where x here is the number of pages in the file, if even, or the number of pages in the file plus one, if odd.

You can obtain the page count with

cpdf -pages foo.pdf

Then the resulting files can be merged.

johnwhitington
  • 2,308
  • 1
  • 16
  • 18