Printing PDF file as per the counts specified in Excel sheet

nitkot

New Member
Joined
May 2, 2023
Messages
21
Office Version
  1. 2019
Platform
  1. Windows
  2. Mobile
  3. Web
We are non-profit organization, which is sending the question papers of religious exam to various schools based on their enrollment of levels.

We need one code, which can print/export to combined PDF based on the parameters given in the excel sheet.

Please check the attached excel sheet for parameters. At break of every school change, system can print one banner page with school name.
 

Attachments

  • Screenshot_6.png
    Screenshot_6.png
    24.5 KB · Views: 13
While running, Unfortunately, code is sending three PDF(s) of the school name heading only, it does not extend the header PDF file with the mentioned files that many times as defined in the excel sheet.
The printing of the banner pages succeeds because it is done by Excel by printing a sheet (bannerSheet.PrintOut), whereas the printing of the PDF files is done by Windows. Not printing the PDF files suggests an application for printing PDFs isn't installed. When you right-click one of the PDF files in File Explorer, is Print one of the options in the context menu?

Also, when you do that, I need output as single PDF file only with Total number of pages = No. of copies for each file + No. of header page printed. In our sample case, it will be 59 pages + 3 school header page (which is getting printed correctly as of now but in separate files) = Total 62 pages.

Regardless of the answer to my question, it seems you prefer the macro to create a single PDF from all the input PDFs and banner sheet, rather than physically printing the files. This is a better approach because we can guarantee the correct order of the combined PDF. To combine (merge) multiple PDFs you need a tool such as PDFtk Server, which can be called from VBA. If you're OK with installing PDFtk Server, I can modify the macro - let me know.

If you can share me your email id, I can send the sample PDF and Excel sheet also.
No need for that because I already have sample PDFs and created your sheet.
 
Upvote 0

Excel Facts

How to total the visible cells?
From the first blank cell below a filtered data set, press Alt+=. Instead of SUM, you will get SUBTOTAL(9,)
If you're OK with installing PDFtk Server, I can modify the macro - let me know.
Yes, I am fine. I think now my requirement is very clear. Thanks a lot for your support.
 
Upvote 0
When you right-click one of the PDF files in File Explorer, is Print one of the options in the context menu?
I do have adobe PDF viewer installed, but "Print" option does not gets displayed on Right click of PDF file in file explorer.
 
Upvote 0
Hi John,

Just recollected one point, School usually prints the papers in Double side printer, so when we create a merged PDF we have to take care to skip one blank page for individual PDF having page count as 1 or 3 or 5 (all odd number pages).

If you can think of that logic. If you find it difficult to know the number of pages in individual PDF, I can create a column for number of pages against each PDF file.

Let me know.
Thanks
Nitin
 
Upvote 0
Just recollected one point, School usually prints the papers in Double side printer, so when we create a merged PDF we have to take care to skip one blank page for individual PDF having page count as 1 or 3 or 5 (all odd number pages).
OK, I understand. Part of the macro below creates BLANK.pdf and adds it to the list of PDFs to be merged after any individual PDF which has an odd number of pages.

On the same basis, I assume each school header PDF should be 2 pages long. This is done by the line starting headerSheet.Range("A1:I60").ExportAsFixedFormat Type:=xlTypePDF. Simply change this range if it doesn't produce a 2-page PDF on your computer.

If you find it difficult to know the number of pages in individual PDF, I can create a column for number of pages against each PDF file.

Fortunately, the dump_data command in PDFtk Server can be run to determine the number of pages in a PDF with a bit of extra code.

Here's the complete code which uses PDFtk Server to merge the PDFs to a single PDF named "All Schools Merged.pdf". Note that your data must be in a 3-column table on the active sheet - you should convert the data range to a table if necessary.

VBA Code:
Option Explicit

Const Q As String = """"

Public Sub Merge_All_School_PDFs()

    Dim PDFsTable As ListObject
    Dim headerSheet As Worksheet
    Dim PDFsFolder As String, inputPDFs As String, FinalMergedPDF As String
    Dim i As Long, n As Long
    Dim school As String
    Dim numPages As Long
    Dim command As String
    Dim Wsh As Object 'WshShell
    
    Set PDFsTable = ActiveSheet.ListObjects(1)
    
    'Add temporary sheet which will be exported to PDF for each school's 2-page header
    
    Set headerSheet = ThisWorkbook.Worksheets.Add(Before:=ThisWorkbook.Worksheets(1))
    
    With PDFsTable
    
        PDFsFolder = Left(.DataBodyRange(1, 2).Value, InStrRev(.DataBodyRange(1, 2).Value, "\"))
        FinalMergedPDF = PDFsFolder & "All Schools Merged.pdf"
        
        'Create BLANK.pdf which is added to list of PDFs to be merged for input PDFs which have an odd number of pages
        
        headerSheet.Range("A1").ExportAsFixedFormat Type:=xlTypePDF, Filename:=PDFsFolder & "BLANK.pdf", _
                        Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
            
        inputPDFs = ""
        school = ""
        For i = 1 To .DataBodyRange.Rows.Count
            If .DataBodyRange(i, 1).Value <> school Then
                'School has changed - update header sheet and export it as PDF with 2 pages
                school = .DataBodyRange(i, 1).Value
                With headerSheet.Range("C25")
                    .Clear
                    .Value = school
                    .Font.Name = "Calibri"
                    .Font.Size = 72
                    .Font.Bold = True
                End With
                headerSheet.Range("A1:I60").ExportAsFixedFormat Type:=xlTypePDF, Filename:=PDFsFolder & school & " HEADER.pdf", _
                    Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
                'Add school header PDF to list of PDFs to be merged
                inputPDFs = inputPDFs & Q & school & " HEADER.pdf" & Q & " "
            End If
            
            'Get number of pages in this PDF
            numPages = GetNumPages(.DataBodyRange(i, 2).Value)
           
            'Add PDF file in column 2 the number of times specified in column 3 to list of PDFs to be merged
            For n = 1 To .DataBodyRange(i, 3).Value
                inputPDFs = inputPDFs & Q & Mid(.DataBodyRange(i, 2).Value, InStrRev(.DataBodyRange(i, 2).Value, "\") + 1) & Q & " "
                If numPages Mod 2 <> 0 Then
                    'This PDF file has an odd number of pages so add BLANK.pdf to list of PDFs to be merged
                    inputPDFs = inputPDFs & Q & "BLANK.pdf" & Q & " "
                End If
            Next
        Next
        
    End With
   
    Application.DisplayAlerts = False
    headerSheet.Delete
    Application.DisplayAlerts = True
       
    'Merge all input PDFs with PDFtk Server cat command
    
    command = "CD /D " & Q & PDFsFolder & Q & " & PDFtk " & inputPDFs & "cat output " & Q & FinalMergedPDF & Q
    Debug.Print command
    Set Wsh = New WshShell
    Wsh.Run "cmd /c " & command, 0, True
    
    'Delete all the school header PDFs and BLANK.pdf
    
    Wsh.Run "cmd /c DEL " & Q & PDFsFolder & "* HEADER.pdf" & Q, 0, True
    Wsh.Run "cmd /c DEL " & Q & PDFsFolder & "BLANK.pdf" & Q, 0, True
    
    MsgBox "Created " & FinalMergedPDF, vbInformation
    
End Sub


Private Function GetNumPages(PDFfullName As String) As Long

    Dim Wsh As Object 'WshShell
    Dim dataFile As String
    Dim command As String
    Dim fileNum As Integer
    Dim allText As String
    
    'Run PDFtk dump_data command to get number of pages in this PDF
    
    dataFile = Left(PDFfullName, InStrRev(PDFfullName, "\")) & "dump_data.txt"
    
    command = "PDFtk " & Q & PDFfullName & Q & " dump_data output " & Q & dataFile & Q
    Set Wsh = CreateObject("WScript.Shell")  'New WshShell
    Wsh.Run "cmd /c " & command, 0, True
    
    fileNum = FreeFile
    Open dataFile For Input As fileNum
    allText = Input(LOF(fileNum), fileNum)
    Close fileNum
    
    GetNumPages = Split(Split(allText, "NumberOfPages: ")(1), vbCrLf)(0)
    
    Kill dataFile
    
End Function
 
Upvote 0
Hi John,
Thanks for your code, Unfortunately, it is giving error at one of the line. I am really new to Macro, so need your assistance in resolving the same. Check the attached screen shot. School header page should be one black page only printing the school name as defined in excel sheet in the middle of page in big font, which was happening correctly earlier it seems. I could not able to test further.

I really appreciate your effort.

Thanks
Nitin
 

Attachments

  • Screenshot_9.png
    Screenshot_9.png
    108.8 KB · Views: 3
Upvote 0
Sorry, I missed that when changing the code from early to late binding. Replace the line with:
VBA Code:
    Set Wsh = CreateObject("WScript.Shell")  'New WshShell
 
Upvote 0
Sorry, I missed that when changing the code from early to late binding. Replace the line with:
VBA Code:
    Set Wsh = CreateObject("WScript.Shell")  'New WshShell
Hi John,

I have changed the code as suggested, it went ahead. Thanks for your help.

Unfortunately, it gave runtime error, Check the attached screen shot. I have installed the PDFtk application on my desktop.

Can you please guide?
 

Attachments

  • Screenshot_10.png
    Screenshot_10.png
    140.4 KB · Views: 4
Upvote 0
I'm guessing that the PDFtk dump_data command doesn't have write access (and maybe read access too) to your C:\Users\nitin\Dropbox\DSB\ folder - the command should create dump_data.txt in that folder, but if the file doesn't exist because it wasn't created you'll get that error. Please check whether C:\Users\nitin\Dropbox\DSB\dump_data.txt exists or not.

As a test, open a command prompt window and enter this command:

Code:
PDFtk "C:\Users\nitin\Dropbox\DSB\01 - 2023 - MM - Hindi - shren1.pdf" dump_data output "C:\Users\nitin\Dropbox\DSB\dump_data.txt"

and let me know if any errors occur and whether "C:\Users\nitin\Dropbox\DSB\dump_data.txt" exists or not.

If it doesn't exist then it's likely that the PDFtk cat command, which later merges all the PDF files, will also fail because it reads from and writes to the same folder.

The easiest solution, without changing the code, is to put the PDF files in a local folder, e.g. C:\School PDFs\ and change the folder paths of the files in column B accordingly.
 
Upvote 0
and let me know if any errors occur and whether "C:\Users\nitin\Dropbox\DSB\dump_data.txt" exists or not.
I gave this command as suggested and dump file is created properly. Check the screen shot herewith.
Good news - Once file has been created successfully as I have commented calling that function and given all page number as 2, I will remove that once corrected.
Now, we only have to check why it's giving runtime error 53.

I am feeling very sorry to disturb you for all this, I am really grateful to you.

Thanks
 

Attachments

  • Screenshot_11.png
    Screenshot_11.png
    41.4 KB · Views: 2
  • Screenshot_12.png
    Screenshot_12.png
    39.2 KB · Views: 2
Upvote 0

Forum statistics

Threads
1,215,679
Messages
6,126,182
Members
449,296
Latest member
tinneytwin

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top