使用Powershell将文本文件的文件夹打印为PDF(保留原始基本名称) [英] Using Powershell to Print a Folder of Text files to PDF (Retaining the Original Base name)

查看:341
本文介绍了使用Powershell将文本文件的文件夹打印为PDF(保留原始基本名称)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首次发布-但我认为这是一个不错的选择,因为我花了2天的时间进行研究,与当地专家进行了交谈,但仍然没有做到这一点.

First time posting - but I think this is a good one as I've spent 2 days researching, talked with local experts, and still haven't found this done.

必须定期在大量文件(.txt文件)上启动单独的打印作业,并且必须通过打印作业将其转换为保留原始基础的本地文件(即通过PDF打印机)每个文件的名称.此外,该脚本必须具有高度的可移植性.

如果仅转换文件(而不打印文件),不保留原始基本文件名或打印过程要求每次打印都需要人工交互,则无法达到目标.

The objective will not be met if the file is simply converted (and not printed), the original base file name is not retained, or the print process requires manual interaction at each print.

研究之后,PowerShell到目前为止是这样:

After my research, this is what stands so far in PowerShell:

问题::该脚本除了实际打印文件内容以外,不执行任何其他操作. 遍历文件,并在保留原始文件名基础的情况下打印" .pdf.但.pdf为空.

PROBLEM: This script does everything but actually print the contents of the file. It iterates through the files, and "prints" a .pdf while retaining the original file name base; but the .pdf is empty.

我知道我错过了一些关键的内容(例如,是否可以使用流?);但经过搜索和搜索后仍无法找到它.任何帮助将不胜感激.

I know I'm missing something critical (i.e. maybe a stream use?); but after searching and searching have not been able to find it. Any help is greatly appreciated.

如代码中所述,打印功能的核心是

As mentioned in the code, the heart of the print function is gathered from this post:

# The heart of this script (ConvertTo-PDF) is largley taken and slightly modified from https://social.technet.microsoft.com/Forums/ie/en-US/04ddfe8c-a07f-4d9b-afd6-04b147f59e28/automating-printing-to-pdf?forum=winserverpowershell
# The $OutputFolder variable can be disregarded at the moment. It is an added bonus, and a work in progress, but not cirital to the objective.
function ConvertTo-PDF {
    param(
        $TextDocumentPath, $OutputFolder
    )

      Write-Host "TextDocumentPath = $TextDocumentPath"
      Write-Host "OutputFolder = $OutputFolder"
    Add-Type -AssemblyName System.Drawing
    $doc = New-Object System.Drawing.Printing.PrintDocument
    $doc.DocumentName = $TextDocumentPath
    $doc.PrinterSettings = new-Object System.Drawing.Printing.PrinterSettings
    $doc.PrinterSettings.PrinterName = 'Microsoft Print to PDF'
    $doc.PrinterSettings.PrintToFile = $true
    $file=[io.fileinfo]$TextDocumentPath
      Write-Host "file = $file"
    $pdf= [io.path]::Combine($file.DirectoryName, $file.BaseName) + '.pdf'
      Write-Host "pdf = $pdf"
    $doc.PrinterSettings.PrintFileName = $pdf
    $doc.Print()
      Write-Host "Attempted Print: $pdf" 
    $doc.Dispose()
}

# get the relative path of the TestFiles and OutpufFolder folders.

$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
  Write-Host "scriptPath = $scriptPath"
$TestFileFolder = "$scriptPath\TestFiles\"
  Write-Host "TestFileFolder = $TestFileFolder"
$OutputFolder = "$scriptPath\OutputFolder\"
  Write-Host "OutputFolder = $OutputFolder"

# initialize the files variable with content of the TestFiles folder (relative to the script location).

$files = Get-ChildItem -Path $TestFileFolder


# Send each test file to the print job
foreach ($testFile in $files)
{
            $testFile = "$TestFileFolder$testFile"
              Write-Host "Attempting Print from: $testFile" 
              Write-Host "Attemtping Print to  : $OutputFolder"
            ConvertTo-PDF $testFile $OutputFolder
}

推荐答案

您缺少读取文本文件并将文本传递给打印机的处理程序.它被定义为如下所示的脚本块:

You are missing a handler that reads the text file and passes the text to the printer. It is defined as a scriptblock like this:

$PrintPageHandler =
{
    param([object]$sender, [System.Drawing.Printing.PrintPageEventArgs]$ev)

    # More code here - see below for details
}

并被添加到PrintDocument对象中,如下所示:

and is added to the PrintDocument object like this:

$doc.add_PrintPage($PrintPageHandler)

所需的完整代码如下:

$PrintPageHandler =
{
    param([object]$sender, [System.Drawing.Printing.PrintPageEventArgs]$ev)

    $linesPerPage = 0
    $yPos = 0
    $count = 0
    $leftMargin = $ev.MarginBounds.Left
    $topMargin = $ev.MarginBounds.Top
    $line = $null

    $printFont = New-Object System.Drawing.Font "Arial", 10

    # Calculate the number of lines per page.
    $linesPerPage = $ev.MarginBounds.Height / $printFont.GetHeight($ev.Graphics)

    # Print each line of the file.
    while ($count -lt $linesPerPage -and (($line = $streamToPrint.ReadLine()) -ne $null))
    {
        $yPos = $topMargin + ($count * $printFont.GetHeight($ev.Graphics))
        $ev.Graphics.DrawString($line, $printFont, [System.Drawing.Brushes]::Black, $leftMargin, $yPos, (New-Object System.Drawing.StringFormat))
        $count++
    }

    # If more lines exist, print another page.
    if ($line -ne $null) 
    {
        $ev.HasMorePages = $true
    }
    else
    {
        $ev.HasMorePages = $false
    }
}

function Out-Pdf
{
    param($InputDocument, $OutputFolder)

    Add-Type -AssemblyName System.Drawing

    $doc = New-Object System.Drawing.Printing.PrintDocument
    $doc.DocumentName = $InputDocument.FullName
    $doc.PrinterSettings = New-Object System.Drawing.Printing.PrinterSettings
    $doc.PrinterSettings.PrinterName = 'Microsoft Print to PDF'
    $doc.PrinterSettings.PrintToFile = $true

    $streamToPrint = New-Object System.IO.StreamReader $InputDocument.FullName

    $doc.add_PrintPage($PrintPageHandler)

    $doc.PrinterSettings.PrintFileName = "$($InputDocument.DirectoryName)\$($InputDocument.BaseName).pdf"
    $doc.Print()

    $streamToPrint.Close()
}

Get-Childitem -Path "$PSScriptRoot\TextFiles" -File -Filter "*.txt" |
    ForEach-Object { Out-Pdf $_ $_.Directory }

顺便说一句,这是基于此处的官方Microsoft C#示例:

Incidentally, this is based on the official Microsoft C# example here:

PrintDocumentClass

这篇关于使用Powershell将文本文件的文件夹打印为PDF(保留原始基本名称)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆