I have the following problem: a powershell script is to be written that sends me all files in a folder with endings such as e.g. .c .cpp .java .xml etc. into a pdf. each file should start with a new page and the file name should be at the beginning.
Add-Type -Path "C:\Program Files\WindowsPowerShell\Modules\itextsharp\5.5.13.3\lib\itextsharp.dll"
function Merge-FilesToPdf {
param(
[Parameter(Mandatory = $true)]
[string]$SourcePath,
[Parameter(Mandatory = $true)]
[string]$DestinationFile
)
# Create a PDF document
$document = New-Object iTextSharp.text.Document
# Initialize the PDF writer
$writer = [iTextSharp.text.pdf.PdfWriter]::GetInstance($document, [System.IO.File]::Create($DestinationFile))
# Open the PDF document
$document.Open()
try {
# Define the font
$font = [iTextSharp.text.pdf.BaseFont]::CreateFont([iTextSharp.text.pdf.BaseFont]::COURIER, [iTextSharp.text.pdf.BaseFont]::CP1252, [iTextSharp.text.pdf.BaseFont]::EMBEDDED)
# List files in the source directory
$files = Get-ChildItem -Path $SourcePath -File
foreach ($file in $files) {
# Check if the file is a text file
if ($file.Extension -match '\.(txt|c|log|xml|ps1)$') {
# Create a new page
$document.NewPage()
# Add the file name as text
$header = New-Object iTextSharp.text.Paragraph($file.Name)
$header.Font = $font # Set font for the file name
$document.Add($header)
# Add the file content to the PDF
$content = Get-Content -Path $file.FullName -Raw
$paragraph = New-Object iTextSharp.text.Paragraph($content)
$paragraph.Font = $font # Set font for the file content
$document.Add($paragraph)
}
}
}
finally {
# Close the PDF document and release memory
$document.Close()
$writer.Close()
$document.Dispose()
$writer.Dispose()
}
}
Merge-FilesToPdf -SourcePath "C:\Projekt\test\kl01\erg001" -DestinationFile "C:\Output.pdf"
This code is finally working, it just doesn't do the formatting in the pdf files like they are in the original files. does anyone have an idea how to solve this?
Edit: I mean if I have for example a C code as a source, the code will be left justified in the PDF, tabs will not transfer