一、需求
从用户以PDF形式上传SOP到服务器的文件夹,我们获取PDF的内容,展示到程序中,每一页一张图片,实现轮播图(屏保)的效果。
二、思路
1、首先在服务器创建共享文件夹,利用本地电脑测试可以访问到用户上传的PDF。
2、可以访问到PDF后,将PDF拆分为一张一张图片,保存到本地文件夹。
3、将本地文件夹的文件拿出来,放到PictureBox控件中
4、利用PictureBox控件,间隔一段时间切换图片,实现轮播图的效果
三、问题点
此次需求的难点在于如何将PDF拆分为一张一张图片,本人找了许多方法,均不完整或不完美。最后发现Spire库可以实现该功能,但是免费版本只能转换三张以内的pdf,再多需要利用付费版。以下分享免费版的实现方法。
四、实现
1、引入Spire库
点击导航栏中工具 => NuGet包管理 => 管理解决方案的NuGet程序包
搜索“Free Spire.PDF”,点击“安装”
2、添加引用、变量定义
首先要在Debug文件夹中创建testPicture文件夹,用来保存图片
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using Spire.Pdf;
public partial class frmPictures : Form
{
//图片路径变量,可以通过其他页面传进来
public string sParam2 { get; internal set; }
public string sParam1 { get; internal set; }
//图片List
private List<String> imagePaths = new List<string>();
//控制pictureBox
bool isClosed = false;
//控制图片index
private int currentIndex = 0;
private Timer timer;
//其他方法……
}
3、将PDF转化为图片,并加载到本地文件夹
private void TestPicture_Load(object sender, EventArgs e)
{
isClosed = true;
this.ActiveControl = panel1;
string dynamicFolder = "TEST\\\\" + sParam1.Trim(); // 动态文件夹名
string dynamicFile = sParam2.Trim() + ".pdf";// 动态文件名
PdfDocument pdf = new PdfDocument();
string path = Path.Combine(@"\\\\127.0.0.1", dynamicFolder, dynamicFile);//文件完整地址–127.0.0.1换成服务器的地址
if (File.Exists(path))
{
// 如果文件存在,则加载它
pdf.LoadFromFile(path);
}
else
{
// 如果文件不存在,则关闭页面
this.Close();
}
for(int i = 0;i < pdf.Pages.Count && isClosed; i++)
{
//pdf页面转化为图片,保存在testPicture文件夹下
Image image = pdf.SaveAsImage(i);
image.Save(String.Format(@"testPicture\\Image{0}.png", i));
image.Dispose();
}
pdf.Close();
LoadImages();
LoadImage();
InitializeTimer();
}
4、将图片加载到List中,再通过List加载到PictureBox控件中
//加载图片到List
private void LoadImages()
{
string folderPath = @"testPicture";
string[] files = Directory.GetFiles(folderPath, "*.png");
imagePaths.AddRange(files);
}
//加载图片到pictureBox
private void LoadImage()
{
if (imagePaths.Count > 0 && currentIndex < imagePaths.Count && isClosed)
{
pictureBox1.Image = Image.FromFile(imagePaths[currentIndex]);
pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
}
}
5、实现轮播图功能
private void InitializeTimer()
{
timer = new Timer();
timer.Interval = 3000; //每3秒切一张图片
timer.Tick += new EventHandler(Timer_Tick);
timer.Start();
}
private void Timer_Tick(object sender, EventArgs e)
{
if(imagePaths.Count <= 0)
{
return;
}
currentIndex = (currentIndex + 1) % imagePaths.Count; //加载下一张图片
LoadImage(); //加载图片到PictureBox
}
五、总结
至此,将PDF转化为图片的功能基本实现,轮播图的效果也已经实现。要实现屏幕保护的功能可以再创建一个定时器,监控鼠标位置,位置变化后,则关闭该页面。需要注意的是,当页面关闭后,需要清空testPicture文件夹中的图片,清空前需要手动进行垃圾回收。具体实现方法并不复杂,在此不再进行过多赘述。
评论前必须登录!
注册