我想制作一个完全由图像文件夹组成的 PDF 文件,最好不要添加压缩或 cruft。是否有任何程序可以让我通过脚本或 API 手动创作 PDF 文件?重要的是 a) 我的 JPEG 不会被第二次压缩,并且 b) 它们以原始分辨率显示,没有边框。(换句话说,我希望我的 PDF 文件只有在每页上以 0,0 为中心的直接 JPG 图像数据,大小正确。)据我所知,大多数创作程序重新压缩图像并添加他们自己的布局的东西。
不建议胆小的人手动创建 PDF 文件!如果您真的想尝试,我们在我们的博客http://blog.idrsolutions.com/2010/09/grow-your-own-pdf-file-part-1-pdf上写了一个关于手工创建 PDF 文件的系列文章-对象和数据类型/
我想,你说的“手动”让一些人感到困惑。您实际上并不是说要编写原始 PDF,对吗?下面是使用开源iTextSharp 库(5.1.1.0) 的代码。将变量设置为FolderWithImages
包含图像的文件夹和PdfFileName
要删除的 PDF,它将获取文件夹中的所有 JPG 并创建一个 PDF。这段代码非常简单,但你可以做很多事情,比如调整大小、缩放等。 iTextSharp 及其父项目 iText 有大量代码。
using System;
using System.ComponentModel;
using System.IO;
using System.Windows.Forms;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//The folder containing our images
string FolderWithImages = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
//The PDF that we will output
string PdfFileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "ImagesCombined.pdf");
//Create a basic stream to write to
using (FileStream fs = new FileStream(PdfFileName, FileMode.Create, FileAccess.Write, FileShare.None))
{
//Create a new PDF document
using (Document doc = new Document())
{
//Bind a the document to the stream
using (PdfWriter w = PdfWriter.GetInstance(doc, fs))
{
//Open our document for writing
doc.Open();
//Will hold an instance of our image
iTextSharp.text.Image img;
//Grab all JPGs from the given folder and loop through them
string[] Images = Directory.GetFiles(FolderWithImages, "*.jpg", SearchOption.TopDirectoryOnly);
foreach (string i in Images)
{
//Get the JPG as an iTextSharp "image"
img = iTextSharp.text.Image.GetInstance(i);
//Tell the image that when placed we want it at (0,0)
img.SetAbsolutePosition(0, 0);
//Tell the system that the next "page" that we add should be the dimension of the image
doc.SetPageSize(new iTextSharp.text.Rectangle(0, 0, img.Width, img.Height));
//Add a new blank page
doc.NewPage();
//Put the image on the blank page
doc.Add(img);
}
//Close our output PDF
doc.Close();
}
}
}
this.Close();
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
13647 次 |
最近记录: |