1.新建一windows服务工程,添加服务文件PDFConverter
partial class PDFConverter : ServiceBase
{
public PDFConverter()
{
InitializeComponent();
}
private System.Timers.Timer timer;
protected override void OnStart(string[] args)
{
timer = new System.Timers.Timer(2000);
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.Start();
}
void timer_Elapsed(object sender, ElapsedEventArgs e)
{
Thread thread = new Thread(new ThreadStart(Process));
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
protected override void OnStop()
{
timer.Stop();
}
[STAThread]
protected void Process()
{
string pdfFilePath = ConfigurationManager.AppSettings["pdfFilepath"];
string imagePath = ConfigurationManager.AppSettings["imageFilepath"];
DirectoryInfo directory = new DirectoryInfo(pdfFilePath);
if (directory == null)
return;
if (!Directory.Exists(imagePath))
Directory.CreateDirectory(imagePath);
FileInfo[] files = directory.GetFiles("*.pdf");
if (files.Length > 0)
{
foreach (FileInfo file in files)
{
if (file.FullName.EndsWith(".pdf"))
{
string pdfFileName = imagePath + file.Name;
if (!File.Exists(pdfFileName) || File.GetCreationTime(pdfFileName) < file.CreationTime)
{
IDataObject data = Clipboard.GetDataObject();
File.Copy(file.FullName, pdfFileName, true);
AcroPDDoc doc = new AcroPDDoc();
doc.Open(file.FullName);
int pageCount = doc.GetNumPages();
for (int i = 0; i < pageCount; i++)
{
AcroPDPage page = (AcroPDPage)doc.AcquirePage(i);
AcroPoint point = (AcroPoint)page.GetSize();
AcroRectClass rect = new AcroRectClass();
rect.Top = rect.Left = 0;
rect.right = point.x;
rect.bottom = point.y;
try
{
bool ok = page.CopyToClipboard(rect, 0, 0, 100);
if (ok)
{
IDataObject pdfData = Clipboard.GetDataObject();
string[] formats = pdfData.GetFormats();
Bitmap bitmap = (Bitmap)pdfData.GetData(DataFormats.Bitmap);
if (bitmap != null)
{
bitmap.Save(imagePath + file.Name.Substring(0, file.Name.Length - 4) + i.ToString() + ".jpg");
bitmap.Dispose();
}
}
}
catch { }
finally
{
Marshal.ReleaseComObject(page);
Marshal.ReleaseComObject(point);
}
}
Clipboard.Clear();
Marshal.ReleaseComObject(doc);
if (data != null)
Clipboard.SetDataObject(data);
}
}
}
}
}
}
2.增加InstallerClass文件
[RunInstaller(true)]
public partial class ProjectInstaller : Installer
{
public ProjectInstaller()
{
InitializeComponent();
}
private void ProjectInstaller_AfterInstall(object sender, InstallEventArgs e)
{
RegistryKey rk = Registry.LocalMachine;
string key = @"SYSTEMCurrentControlSetServices" + this.serviceInstaller1.ServiceName;
RegistryKey sub = rk.CreateSubKey(key);
sub.CreateSubKey("Type");
int value = (int)sub.GetValue("Type");
sub.SetValue("Type", value | 256);
}
}
3.增加一个Setup工程创建安装程序,安装服务后配置AppConfig.config中的目录信息,启动服务。每隔2s服务检查PDF文件目录对新增文件自动进行转换。
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="pdfFilepath" value="D:PDFPath"/>
<add key="imageFilepath" value="D:ImagePath"/>
</appSettings>
</configuration>