文件名命名为xxx.ps1
源文件夹的文件名复制方式: 按住shift, 右键对应文件夹, 选择复制文件路径, 然后粘贴到这里
目标文件夹这里也改一下就可以
最好是先备份一下源文件们, 万无一失.
# 设置源文件夹和目标文件夹
$sourceRoot = "C:\Users\Administrator\Pictures\test1" # 改成你的源文件夹路径
$targetRoot = "C:\Users\Administrator\Pictures\test2" # 改成你的目标文件夹路径
# 创建目标文件夹
New-Item -ItemType Directory -Force -Path $targetRoot
# 为每个子文件夹创建HTML和PDF
Get-ChildItem -Path $sourceRoot -Directory | ForEach-Object {
$folderName = $_.Name
Write-Host "处理文件夹: $folderName"
Write-Host "当前处理路径: $($_.FullName)"
# 获取所有图片(更详细的文件查找)
$images = Get-ChildItem -Path $_.FullName -File | Where-Object {
$_.Extension -match '\.(jpg|jpeg|png|gif)$'
}
Write-Host "找到图片数量: $($images.Count)"
foreach ($img in $images) {
Write-Host "发现图片: $($img.Name)"
}
if ($images.Count -eq 0) {
Write-Host "警告: 文件夹 $folderName 中没有找到图片"
continue
}
# 创建临时HTML
$html = @"
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
body { margin: 0; padding: 20px; background-color: white; }
.img-container {
width: 100%;
margin: 20px 0;
page-break-after: always;
text-align: center;
}
img {
max-width: 90%;
height: auto;
display: inline-block;
}
</style>
</head>
<body>
"@
# 添加图片到HTML
foreach ($img in $images) {
try {
Write-Host "正在处理图片: $($img.FullName)"
$base64 = [convert]::ToBase64String((Get-Content $img.FullName -Encoding Byte -ErrorAction Stop))
$ext = $img.Extension.Substring(1) # 移除点号
$html += "<div class='img-container'><img src='data:image/$ext;base64,$base64'></div>`n"
}
catch {
Write-Host "处理图片时出错: $($img.Name)"
Write-Host $_.Exception.Message
}
}
$html += "</body></html>"
# 保存临时HTML
$tempHtml = Join-Path $env:TEMP "temp_$($folderName).html"
$html | Out-File -FilePath $tempHtml -Encoding UTF8
# 输出PDF路径
$pdfPath = Join-Path $targetRoot "$folderName.pdf"
Write-Host "正在转换为PDF: $pdfPath"
# 使用Edge转换为PDF
& "C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" `
--headless `
--disable-gpu `
--no-sandbox `
--disable-web-security `
--print-to-pdf="$pdfPath" `
"$tempHtml"
# 等待确保PDF生成完成
Start-Sleep -Seconds 3
# 删除临时HTML
Remove-Item $tempHtml
Write-Host "完成处理: $folderName"
Write-Host "-------------------"
}
Write-Host "所有文件夹处理完成!"
弄完之后呢, 保存, 右键运行就可以了.
Comments NOTHING