Commit 43d8e71d by songxiang

删除ActiveMQ相关的代码和配置

parent 42a94a4b
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.pcloud.common</groupId>
<artifactId>pcloud-common-parent</artifactId>
<version>2.1.0-RELEASE</version>
</parent>
<artifactId>pcloud-common-core</artifactId>
<packaging>jar</packaging>
<version>${pcloud-common-core.version}</version>
<name>pcloud-common-core</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.pcloud.common</groupId>
<artifactId>pcloud-common</artifactId>
<version>${pcloud-common.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<!-- Database connect Begin -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>
<!-- Database connect End -->
<!-- Mysql Driver Begin -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- Mysql Driver End -->
<!-- ActiveMq Begin -->
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
</dependency>
<!-- ActiveMq End -->
<!-- Jackson Begin -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
</dependency>
<!-- Jackson End -->
<!-- Redis Begin -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<!-- Redis End -->
</dependencies>
</project>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.pcloud.common</groupId>
<artifactId>pcloud-common-parent</artifactId>
<version>2.1.0-RELEASE</version>
</parent>
<artifactId>pcloud-common-core</artifactId>
<packaging>jar</packaging>
<version>${pcloud-common-core.version}</version>
<name>pcloud-common-core</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.pcloud.common</groupId>
<artifactId>pcloud-common</artifactId>
<version>${pcloud-common.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<!-- Database connect Begin -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>
<!-- Database connect End -->
<!-- Mysql Driver Begin -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- Mysql Driver End -->
<!-- Jackson Begin -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
</dependency>
<!-- Jackson End -->
</dependencies>
</project>
/**
*
*
*/
package com.pcloud.common.core.constant;
/**
*
*
* @author:songx
* @date:2017年2月27日,下午4:29:06
*
* 使用RabbitMQ需要去MqQueueConstant中声明队列名称,枚举的第二个值将不再使用,第一个值正常使用
* @date:2017年2月27日,下午4:29:06 使用RabbitMQ需要去MqQueueConstant中声明队列名称,枚举的第二个值将不再使用,第一个值正常使用
* modify by songx at 2018-08-22
*/
public enum ConvertEnum {
/**
* 应用转码
*/
APP("APP", "convert2App"),
/**
* 资源中心转码
*/
RESOURCE("RESOURCE", "convert2Resource"),
/**
* 报名时的视频转换
*/
MATCH("MATCH", "convert2Resource"),
/**
* 资源中心即时转换
*/
INSTANT_RESOURCE("INSTANT_RESOURCE", "convert2Resource"),
/**
* 报名应用
*/
MATCH_APP("MATCH_APP", "convert2MatchApp"),
/**
* 内容中心
*/
CONTENT("CONTENT", "convert2Content"),
/**
* 内容中心->题库:文件记忆功能
*/
PRETEST_FILEMEMORY("PRETEST_FILEMEMORY", "convert2PretestFilememory"),
/**
* 小游戏
*/
RAYSTASK("RAYSTASK", "convert2Raystask"),
/**
* 圈子应用
*/
GROUP_APP("GROUP_APP", "convert2GroupApp"),
/**
* 投票应用
*/
VOTE_APP("VOTE_APP", "convert2VoteApp"),
/**
* 教育表格应用
*/
EF_APP("EF_APP", "convert2EfApp"),
/**
* 测试工具
*/
TEST_APP("TEST_APP", "convert2TestApp"),
/**
* 直播工具
*/
LIVE_APP("LIVE_APP", "convert2LiveApp"),
/**
* 视频课
*/
VIDEO_LESSON("VIDEO_LESSON", "convert2VideoLesson"),
/**
* 应用转码
*/
APP("APP"),
/**
* 资源中心转码
*/
RESOURCE("RESOURCE"),
/**
* 报名时的视频转换
*/
MATCH("MATCH"),
/**
* 资源中心即时转换
*/
INSTANT_RESOURCE("INSTANT_RESOURCE"),
/**
* 报名应用
*/
MATCH_APP("MATCH_APP"),
/**
* 内容中心
*/
CONTENT("CONTENT"),
/**
* 内容中心->题库:文件记忆功能
*/
PRETEST_FILEMEMORY("PRETEST_FILEMEMORY"),
/**
* 小游戏
*/
RAYSTASK("RAYSTASK"),
/**
* 圈子应用
*/
GROUP_APP("GROUP_APP"),
/**
* 投票应用
*/
VOTE_APP("VOTE_APP"),
/**
* 教育表格应用
*/
EF_APP("EF_APP"),
/**
* 测试工具
*/
TEST_APP("TEST_APP"),
/**
* 直播工具
*/
LIVE_APP("LIVE_APP"),
/**
* 视频课
*/
VIDEO_LESSON("VIDEO_LESSON"),
/**
* 音频课
*/
AUDIO_LESSON("AUDIO_LESSON", "convert2AudioLesson"),
AUDIO_LESSON("AUDIO_LESSON"),
/**
* 音频纯听
*/
AUDIO_LISTEN("AUDIO_LISTEN", "convert2AudioListen");
AUDIO_LISTEN("AUDIO_LISTEN");
/**
* 值
*/
public final String value;
/**
* 模板名称
*/
public final String jmsTemplate;
/**
* 构造
*
* @param value
*/
private ConvertEnum(String value, String jmsTemplate) {
this.value = value;
this.jmsTemplate = jmsTemplate;
}
/**
* 构造
*
* @param value
*/
private ConvertEnum(String value) {
this.value = value;
}
}
package com.pcloud.common.core.mq;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jms.connection.CachingConnectionFactory;
import org.springframework.jms.connection.SingleConnectionFactory;
/**
* @描述:
* @作者:songx
* @创建时间:2017年9月14日,上午10:48:02
* @版本:1.0
*/
@Configuration
@PropertySource(value = "classpath:public_system.properties")
public class ActiveMqFactory {
/**
*
*/
private static final Logger LOGGER = LoggerFactory.getLogger(ActiveMqFactory.class);
@Value("${mq.brokerURL}")
private String brokerURL;
/**
* 初始化Mq连接
*
* @return
*/
@Bean(name = "connectionFactory")
public ActiveMQConnectionFactory getMqConnection() {
LOGGER.info("【ActiveMq】初始化MQ链接.<START>");
ActiveMQConnectionFactory mqConnection = new ActiveMQConnectionFactory();
mqConnection.setBrokerURL(brokerURL);
mqConnection.setTrustAllPackages(true);
return mqConnection;
}
/**
* 初始化JMS连接池
*
* @return
*/
@Autowired
@Bean("cachingConnectionFactory")
public CachingConnectionFactory getCachingConnectionFactory(ActiveMQConnectionFactory connectionFactory) {
CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(connectionFactory);
cachingConnectionFactory.setReconnectOnException(true);
cachingConnectionFactory.setCacheConsumers(false);
cachingConnectionFactory.setCacheProducers(false);
cachingConnectionFactory.setSessionCacheSize(50);
return cachingConnectionFactory;
}
/**
* Spring用于管理真正的ConnectionFactory的ConnectionFactory
*
* @return
*/
@Autowired
@Bean(name = "singleConnectionFactory")
public SingleConnectionFactory getSingleConnection(CachingConnectionFactory cachingConnectionFactory) {
LOGGER.info("【ActiveMq】初始化spring管理JMS链接.<START>");
SingleConnectionFactory singleConnection = new SingleConnectionFactory();
singleConnection.setTargetConnectionFactory(cachingConnectionFactory);
return singleConnection;
}
}
package com.pcloud.common.core.mq;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.connection.CachingConnectionFactory;
import org.springframework.jms.core.JmsTemplate;
/**
* @描述:
*
* @作者:songx
* @创建时间:2017年9月14日,上午11:40:25 @版本:1.0
*/
@Configuration
public class ActiveMqProducer {
@Autowired
private CachingConnectionFactory cachingConnectionFactory;
@Autowired(required = false)
@Qualifier("convertQueue")
private ActiveMQQueue convertQueue;
@Autowired(required = false)
@Qualifier("labelUsedQueue")
private ActiveMQQueue labelUsedQueue;
@Autowired(required = false)
@Qualifier("logQueue")
private ActiveMQQueue logQueue;
@Autowired(required = false)
@Qualifier("messageQueue")
private ActiveMQQueue messageQueue;
@Autowired(required = false)
@Qualifier("weektaskQueue")
private ActiveMQQueue weektaskQueue;
@Autowired(required = false)
@Qualifier("templateQueue")
private ActiveMQQueue templateQueue;
@Autowired(required = false)
@Qualifier("userActionQueue")
private ActiveMQQueue userActionQueue;
@Autowired(required = false)
@Qualifier("funnelFlowQueue")
private ActiveMQQueue funnelFlowQueue;
@Autowired(required = false)
@Qualifier("fundQueue")
private ActiveMQQueue fundQueue;
@Autowired(required = false)
@Qualifier("dynamicQueue")
private ActiveMQQueue dynamicQueue;
@Autowired(required = false)
@Qualifier("exapiQueue")
private ActiveMQQueue exapiQueue;
@Autowired(required = false)
@Qualifier("frontEventQueue")
private ActiveMQQueue frontEventQueue;
@Autowired(required = false)
@Qualifier("transcodeQueue")
private ActiveMQQueue transcodeQueue;
@Autowired(required = false)
@Qualifier("promotionTaskQueue")
private ActiveMQQueue promotionTaskQueue;
@Autowired(required = false)
@Qualifier("promotionTerminateQueue")
private ActiveMQQueue promotionTerminateQueue;
/**
* 获取音视频转码JMS
*
* @return
*/
@Bean(name = "jmsConvertTemplate")
public JmsTemplate getConvertTemplate() {
JmsTemplate jmsTemplate = getJmsTemplate();
jmsTemplate.setDefaultDestination(convertQueue);
return jmsTemplate;
}
/**
* 获取标签使用JMS
*
* @return
*/
@Bean(name = "jmsLabelUsedTemplate")
public JmsTemplate getLabelUsedTemplate() {
JmsTemplate jmsTemplate = getJmsTemplate();
jmsTemplate.setDefaultDestination(labelUsedQueue);
return jmsTemplate;
}
/**
* 获取日志JMS
*
* @return
*/
@Bean(name = "jmsLogTemplate")
public JmsTemplate getLogTemplate() {
JmsTemplate jmsTemplate = getJmsTemplate();
jmsTemplate.setDefaultDestination(logQueue);
return jmsTemplate;
}
/**
* 获取消息JMS
*
* @return
*/
@Bean(name = "jmsMessageTemplate")
public JmsTemplate getMessageTemplate() {
JmsTemplate jmsTemplate = getJmsTemplate();
jmsTemplate.setDefaultDestination(messageQueue);
return jmsTemplate;
}
/**
* 获取编辑任务JMS
*
* @return
*/
@Bean(name = "jmsWeektaskTemplate")
public JmsTemplate getWeektaskTemplate() {
JmsTemplate jmsTemplate = getJmsTemplate();
jmsTemplate.setDefaultDestination(weektaskQueue);
return jmsTemplate;
}
/**
* 获取模板消息JMS
*
* @return
*/
@Bean(name = "jmsTemplateTemplate")
public JmsTemplate getTemplateTemplate() {
JmsTemplate jmsTemplate = getJmsTemplate();
jmsTemplate.setDefaultDestination(templateQueue);
return jmsTemplate;
}
/**
* 获取用户行为JMS
*
* @return
*/
@Bean(name = "jmsUserActionTemplate")
public JmsTemplate getUserActionTemplate() {
JmsTemplate jmsTemplate = getJmsTemplate();
jmsTemplate.setDefaultDestination(userActionQueue);
return jmsTemplate;
}
/**
* 获取漏斗流程JMS
*
* @return
*/
@Bean(name = "jmsFunnelFlowTemplate")
public JmsTemplate getFunnelFlowTemplate() {
JmsTemplate jmsTemplate = getJmsTemplate();
jmsTemplate.setDefaultDestination(funnelFlowQueue);
return jmsTemplate;
}
/**
* 基金修改监控JMS
*
* @return
*/
@Bean(name = "jmsFundTemplate")
public JmsTemplate getJmsFundTemplate() {
JmsTemplate jmsTemplate = getJmsTemplate();
jmsTemplate.setDefaultDestination(fundQueue);
return jmsTemplate;
}
/**
* 作者动态监控JMS
*
* @return
*/
@Bean(name = "jmsDynamicTemplate")
public JmsTemplate getJmsDynamicTemplate() {
JmsTemplate jmsTemplate = getJmsTemplate();
jmsTemplate.setDefaultDestination(dynamicQueue);
return jmsTemplate;
}
/**
* 收集事件
*
* @return
*/
@Bean(name = "jmsFrontEventTemplate")
public JmsTemplate getJmsFrontEventTemplate() {
JmsTemplate jmsTemplate = getJmsTemplate();
jmsTemplate.setDefaultDestination(frontEventQueue);
return jmsTemplate;
}
/**
* 对外api监控JMS
*
* @author wangrui
* @date 10:40 2018/4/13
*/
@Bean(name = "jmsExapiTemplate")
public JmsTemplate getJmsExapiTemplate() {
JmsTemplate jmsTemplate = getJmsTemplate();
jmsTemplate.setDefaultDestination(exapiQueue);
return jmsTemplate;
}
/**
* 文件转码JMS
*
* @return
*/
@Bean(name = "jmsTranscodeTemplate")
public JmsTemplate getJmsTranscodeTemplate() {
JmsTemplate jmsTemplate = getJmsTemplate();
jmsTemplate.setDefaultDestination(transcodeQueue);
return jmsTemplate;
}
/**
* 获取促销任务JMS
*
* @return
*/
@Bean(name = "jmsPromotionTaskTemplate")
public JmsTemplate getJmsPromotionTaskTemplate() {
JmsTemplate jmsTemplate = getJmsTemplate();
jmsTemplate.setDefaultDestination(promotionTaskQueue);
return jmsTemplate;
}
/**
* 获取促销终止JMS
*
* @return
*/
@Bean(name = "jmsPromotionTerminateTemplate")
public JmsTemplate getJmsPromotionTerminateTemplate() {
JmsTemplate jmsTemplate = getJmsTemplate();
jmsTemplate.setDefaultDestination(promotionTerminateQueue);
return jmsTemplate;
}
/**
* 获取JMS模板
*
* @return
*/
private JmsTemplate getJmsTemplate() {
JmsTemplate jmsTemplate = new JmsTemplate(cachingConnectionFactory);
jmsTemplate.setReceiveTimeout(10000);
return jmsTemplate;
}
}
package com.pcloud.common.core.mq;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.pcloud.common.core.enums.MqQueueEnum;
/**
*
* @描述:
*
* @作者:songx
* @创建时间:2017年11月14日,上午10:59:55 @版本:1.0
*/
@Configuration
public class ActiveMqQueue {
/**
* 音视频转换消息队列
*
* @return
*/
@Bean(name = "convertQueue")
public ActiveMQQueue getConvertQueue() {
return new ActiveMQQueue("convert");
}
/**
* 标签使用量消息队列
*
* @return
*/
@Bean(name = "labelUsedQueue")
public ActiveMQQueue getLabelUsedQueue() {
return new ActiveMQQueue("labelUsed");
}
/**
* 日志消息队列
*
* @return
*/
@Bean(name = "logQueue")
public ActiveMQQueue getLogQueue() {
return new ActiveMQQueue("log");
}
/**
* 系统消息消息队列
*
* @return
*/
@Bean(name = "messageQueue")
public ActiveMQQueue getMessageQueue() {
return new ActiveMQQueue("message");
}
/**
* 周任务消息队列
*
* @return
*/
@Bean(name = "weektaskQueue")
public ActiveMQQueue getWeektaskQueue() {
return new ActiveMQQueue("weektask");
}
/**
* 模板消息消息队列
*
* @return
*/
@Bean(name = "templateQueue")
public ActiveMQQueue getTemplateQueue() {
return new ActiveMQQueue("template");
}
/**
* 用户行为消息队列
*
* @return
*/
@Bean(name = "userActionQueue")
public ActiveMQQueue getUserActionQueue() {
return new ActiveMQQueue("userAction");
}
/**
* 用户漏斗流程队列
*
* @return
*/
@Bean(name = "funnelFlowQueue")
public ActiveMQQueue getFunnelFlowQueue() {
return new ActiveMQQueue("funnelFlow");
}
/**
* 基金监控消息队列
*
* @return
*/
@Bean(name = "fundQueue")
public ActiveMQQueue getFundQueue() {
return new ActiveMQQueue("fund");
}
/**
* 动态监控消息队列
*
* @return
*/
@Bean(name = "dynamicQueue")
public ActiveMQQueue getDynamicQueue() {
return new ActiveMQQueue("merchantDynamic");
}
/**
* 事件分析埋点
*
* @return
*/
@Bean(name = "frontEventQueue")
public ActiveMQQueue getFrontEventQueue() {
return new ActiveMQQueue("frontEvent");
}
/**
* 对外api队列
*
* @author wangrui
* @date 10:28 2018/4/13
*/
@Bean(name = "exapiQueue")
public ActiveMQQueue getExapiQueue() {
return new ActiveMQQueue("exapi");
}
/**
* 文件转码(非音视频转码)
*
* @return
*/
@Bean(name = "transcodeQueue")
public ActiveMQQueue getTranscodeQueue() {
return new ActiveMQQueue(MqQueueEnum.TRANSCODE.queueName);
}
/**
* 促销任务
*
* @return
*/
@Bean(name = "promotionTaskQueue")
public ActiveMQQueue getPromotionTaskQueue() {
return new ActiveMQQueue("promotionTask");
}
/**
* 促销终止
*
* @return
*/
@Bean(name = "promotionTerminateQueue")
public ActiveMQQueue getPromotionTerminateQueue() {
return new ActiveMQQueue("promotionTerminate");
}
}
......@@ -203,6 +203,13 @@
</dependency>
<!-- sftp end -->
<!-- google Begin -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<!-- google End -->
<!-- ftp begin -->
<dependency>
<groupId>commons-net</groupId>
......@@ -241,12 +248,6 @@
<artifactId>freemarker</artifactId>
</dependency>
<!-- PDF解析工具 -->
<dependency>
<groupId>pcloud.tools</groupId>
<artifactId>tools</artifactId>
</dependency>
<!-- 图片处理工具 added by songx at 2017-05-17 -->
<dependency>
<groupId>net.coobird</groupId>
......@@ -297,12 +298,6 @@
</dependency>
<!-- end -->
<!-- google 工具包 -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<!-- Jackson Begin -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
......@@ -378,12 +373,7 @@
<version>1.5.2</version>
</dependency>
<!--PDF转图片 -->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.9</version>
</dependency>
<dependency>
<groupId>com.github.jai-imageio</groupId>
......
package com.pcloud.common.utils.pdf;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.google.common.collect.Lists;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
import com.pcloud.common.constant.FilePathConst;
import com.pcloud.common.entity.UploadResultInfo;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.exceptions.FileException;
import com.pcloud.common.utils.FileUtils;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.UUIDUitl;
import com.pcloud.common.utils.aliyun.OssUtils;
import com.pcloud.common.utils.pdf.po.PdfChunkPO;
import com.pcloud.common.utils.pdf.po.PdfImagePO;
import com.pcloud.common.utils.pdf.po.PdfPO;
import com.pcloud.common.utils.pdf.po.PdfTablePO;
import com.pcloud.common.utils.string.StringUtil;
import com.pcloud.tools.pdf.convert.image.PdfToImage;
import javax.imageio.ImageIO;
/**
* @author Administrator
*/
@Component("pdfUtils")
public class PdfUtils {
/**
*
*/
private static final Logger LOGGER = LoggerFactory.getLogger(PdfUtils.class);
/**
* PDF转换图片的宽度
*/
public static final Integer IMAGE_WITH = 1654;
/**
* PDF转换图片的高度
*/
public static final Integer IMAGE_HEIGHT = 2399;
/**
* PDF文件转换图片
*
* @param fileUrl
* @param format
* @return
* @throws Exception
*/
public static List<UploadResultInfo> pdfToImage(String fileUrl, String format) throws FileException {
String fileName = FileUtils.getFileName(fileUrl);
// 下载PDF文件
byte[] bytes = FileUtils.downloadByteFromUrl(fileUrl);
if (bytes == null) {
throw new FileException(FileException.FILE_DOWNLOAD_FAILURE, "下载文件失败");
}
if (bytes.length == 0) {
return Lists.newArrayList();
}
// 解析PDF文件
String outPath = pdfConvert(bytes, fileName, "", format);
// 上传图片文件
return pdfImageUpload(outPath, fileName, format);
}
/**
* PDF文件转换图片
*
* @param fileUrl
* @param format
* @return
*/
public static List<UploadResultInfo> pdf2Image(String fileUrl, String format) {
String fileName = FileUtils.getFileName(fileUrl);
String filePath = FilePathConst.DOWNLOAD_PATH + fileName + "_" + UUIDUitl.generateString(12);
String outputPath = FilePathConst.PDF_PATH + fileName + "_" + UUIDUitl.generateString(12);
try {
FileUtils.downloadFileFromUrl(fileUrl, filePath);
File outputDir = new File(outputPath);
if (!outputDir.exists()) {
outputDir.mkdir();
}
File file = new File(filePath);
if (!file.exists()) {
LOGGER.error(fileUrl + " download error");
throw new FileException(FileException.FILE_DOWNLOAD_FAILURE, "下载文件失败");
}
LOGGER.info("pdf downloaded to Folder: " + outputDir.getName());
PDDocument document = PDDocument.load(new File(filePath));
int total = document.getNumberOfPages();
LOGGER.info("Total images to be converted: " + total);
PDFRenderer render = new PDFRenderer(document);
for (int i = 0; i < total; i++) {
BufferedImage image = render.renderImage(i, 2.0f);
File outputfile = new File(outputPath + "page" + (i + 1) + "." + format);
ImageIO.write(image, format, outputfile);
}
document.close();
LOGGER.info("Converted Images are saved at: " + outputDir.getAbsolutePath());
return pdfImageUpload(outputPath, fileName, format);
} catch (Exception e) {
LOGGER.warn("pdf convert error", e);
return pdfToImage(fileUrl, format);
}
}
/**
* PDF转换文件
*
* @param b
* @param fileName
* @param prefix
* @param format
* @return
* @throws Exception
*/
private static String pdfConvert(byte[] b, String fileName, String prefix, String format) throws FileException {
// 解析PDF文件
String outPath = FilePathConst.PDF_PATH + fileName + "_" + UUIDUitl.generateString(12);
File fi = new File(outPath);
if (!fi.exists()) {
fi.mkdirs();
}
try {
PdfToImage pImage = new PdfToImage(IMAGE_WITH, IMAGE_HEIGHT, prefix, format);
pImage.convertPagesToHiResImages(b, outPath);
} catch (Exception e) {
FileUtils.deleteDirectory(outPath);
LOGGER.error("【PDF】PDF转换图片失败:" + e.getMessage(), e);
throw new FileException(FileException.FILE_CONTENT_ERROR, "PDF转换图片失败");
}
return outPath;
}
/**
* PDF图片上传
*
* @param outPath
* @param format
* @return
* @throws Exception
*/
private static List<UploadResultInfo> pdfImageUpload(String outPath, String fileName, String format)
throws FileException {
List<UploadResultInfo> list = Lists.newArrayList();
try {
File[] fileArray = new File(outPath).listFiles();
for (int i = 0; i < fileArray.length; i++) {
// modify by songx at 2017-05-19
// PDF工具包生成的图片已pageXXX命名,所以取XXX为文件的页数
String childDileName = FileUtils.getFileName(fileArray[i].getName());
int page = Integer.valueOf(childDileName.replace("page", ""));
UploadResultInfo uploadResultInfo = OssUtils.uploadLocalFile4CustomName(fileArray[i].getPath(),
fileName + "_" + page);
if (uploadResultInfo == null) {
throw new FileException(FileException.FILE_CONTENT_ERROR, "PDF转换图片上传失败:第" + i + "张");
}
uploadResultInfo.setFileName(childDileName);
uploadResultInfo.setFileType(format);
uploadResultInfo.setPage(page);
list.add(uploadResultInfo);
}
} catch (Exception e) {
LOGGER.error("【PDF】PDF转换图片上传失败:" + e.getMessage(), e);
throw new FileException(FileException.FILE_UPLOAD_FAILURE, "PDF转换图片上传失败");
} finally {
FileUtils.deleteDirectory(outPath);
}
return list;
}
/**
* 创建PDF
*
* @param pdfChunkDOs
* @return
* @throws Exception
*/
public static String create(List<PdfPO> pdfPOs) throws FileException {
LOGGER.info("【PDF】创建PDF文档,<START>");
if (ListUtils.isEmpty(pdfPOs)) {
return null;
}
String outPath = null;
PdfWriter pdfWriter = null;
Document document = null;
OutputStream os = null;
try {
// 输出路径
outPath = FilePathConst.PDF_PATH + UUIDUitl.taskName() + ".pdf";
FileUtils.creatFiles(outPath);
// 创建输出流
os = new FileOutputStream(new File(outPath));
// 初始化文档
// 设置纸张
Rectangle rect = new Rectangle(PageSize.A4);
// 创建文档实例
document = new Document(rect, 50, 50, 50, 50);
pdfWriter = PdfWriter.getInstance(document, os);
document.open();
document.newPage();
// 添加内容添加PDF实例中
addChunks(pdfPOs, document);
} catch (Exception e) {
FileUtils.deleteFile(outPath);
LOGGER.error("【PDF】创建PDF文档失败:" + e.getMessage(), e);
throw new FileException(FileException.FILE_CONTENT_ERROR, e.getMessage());
} finally {
close(document, os, pdfWriter);
}
LOGGER.info("【PDF】创建PDF文档,<END>");
return outPath;
}
/**
* 添加内容到PDF中
*
* @param pdfPOs
* @param document
* @throws BizException
* @throws DocumentException
* @throws MalformedURLException
* @throws IOException
*/
private static void addChunks(List<PdfPO> pdfPOs, Document document)
throws BizException, DocumentException, MalformedURLException, IOException {
for (PdfPO pdfPO : pdfPOs) {
if (pdfPO instanceof PdfChunkPO) {
addChunk(pdfPO, document);
} else if (pdfPO instanceof PdfTablePO) {
addTable(pdfPO, document);
} else if (pdfPO instanceof PdfImagePO) {
addImage(pdfPO, document);
}
}
}
/**
* 添加块
*
* @param pdfPO
* @throws BizException
* @throws DocumentException
*/
private static void addChunk(PdfPO pdfPO, Document document) throws BizException, DocumentException {
PdfChunkPO pdfChunkPO = (PdfChunkPO) pdfPO;
// 段落
Paragraph paragraph = null;
Font font = PdfFontUtils.getByType(pdfChunkPO.getPdfFontEnum());
if (pdfChunkPO.isLeanding()) {
paragraph = new Paragraph(pdfChunkPO.getText(), font);
paragraph.setLeading(pdfChunkPO.getLeading() > 0 ? pdfChunkPO.getLeading() : Float.NaN);
} else {
paragraph = new Paragraph();
// 短语
Phrase phrase = new Phrase();
// 短语中的某一块
Chunk chunk = new Chunk(StringUtil.isEmpty(pdfChunkPO.getText()) ? "" : pdfChunkPO.getText(), font);
// skew大于0 的时候生效.字体倾斜角度
if (pdfChunkPO.getSkew() > 0) {
chunk.setSkew(0, pdfChunkPO.getSkew());
}
// 将块添加到短语
phrase.add(chunk);
// 将短语添加到段落
paragraph.add(phrase);
}
// 段落前间距
paragraph.setSpacingBefore(pdfChunkPO.getSpacingBefore() > 0 ? pdfChunkPO.getSpacingBefore() : Float.NaN);
// 段落后间距
paragraph.setSpacingAfter(pdfChunkPO.getSpacingAfter() > 0 ? pdfChunkPO.getSpacingAfter() : Float.NaN);
// 段落位置
paragraph.setAlignment(pdfChunkPO.getPdfAlignEnum().value);
// 将段落添加到文档
document.add(paragraph);
}
/**
* 添加表格
*
* @param pdfPO
* @throws BizException
* @throws DocumentException
*/
private static void addTable(PdfPO pdfPO, Document document) throws BizException, DocumentException {
PdfTablePO pdfTablePO = (PdfTablePO) pdfPO;
String[][] contents = pdfTablePO.getContents();
if (contents == null || contents.length < 1) {
return;
}
int rowNum = contents.length; // 总行数
int colNum = pdfTablePO.getColumnWidths().length; // 总列数
if (colNum < 1) {
throw new FileException(FileException.FILE_CONTENT_ERROR, "表格列数与内容列数不一致");
}
// 字体
Font font = PdfFontUtils.getByType(pdfTablePO.getPdfFontEnum());
// 创建表格
PdfPTable table = new PdfPTable(colNum);
table.setTotalWidth(pdfTablePO.getColumnWidths()); // 设置列宽
table.setLockedWidth(true); // 锁定列宽
// 设置行和列
for (int i = 0; i < rowNum; i++) {
String[] cols = contents[i];
for (int j = 0; j < colNum; j++) {
String text = (j >= cols.length || StringUtil.isEmpty(cols[j])) ? "" : cols[j];
// 填充单元格内容
PdfPCell cell = new PdfPCell(new Phrase(text, font));
// 设置上边的边框宽度
cell.setBorderWidthTop(1);
// 设置左边的边框宽度
cell.setBorderWidthLeft(1);
// 设置右边的边框宽度
if (j == (colNum - 1)) {
cell.setBorderWidthRight(1);
}
// 设置底部的边框宽度
if (i == (rowNum - 1)) {
cell.setBorderWidthBottom(1);
}
// 设置单元格高度
cell.setMinimumHeight(pdfTablePO.getMinimumHeight() > 0 ? pdfTablePO.getMinimumHeight() : Float.NaN);
// 设置可以居中
cell.setUseAscender(true);
// 设置水平居中
cell.setHorizontalAlignment(pdfTablePO.getPdfAlignEnum().value);
// 设置垂直居中
cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
table.addCell(cell);
}
}
// 将表格添加到文档
document.add(table);
}
/**
* 添加图片
*
* @param pdfPO
* @param document
* @throws MalformedURLException
* @throws IOException
* @throws DocumentException
*/
private static void addImage(PdfPO pdfPO, Document document)
throws MalformedURLException, IOException, DocumentException {
PdfImagePO pdfImagePO = (PdfImagePO) pdfPO;
Image image = null;
if (!StringUtil.isEmpty(pdfImagePO.getImageUrl())) {
if (pdfImagePO.getImageUrl().startsWith("http")) {
image = Image.getInstance(new URL(pdfImagePO.getImageUrl()));
} else {
image = Image.getInstance(pdfImagePO.getImageUrl());
}
image.setAlignment(pdfImagePO.getPdfAlignEnum().value);
if (pdfImagePO.getHeight() > 0 || pdfImagePO.getWidth() > 0) {
image.scaleAbsolute(pdfImagePO.getHeight(), pdfImagePO.getWidth());
}
} else if (pdfImagePO.getImageByte() != null) {
image = Image.getInstance(pdfImagePO.getImageByte());
} else {
return;
}
// 将表格添加到文档
document.add(image);
}
/**
* 加水印(字符串)
*
* @param inputFile 需要加水印的PDF路径
* @param outputFile 输出生成PDF的路径
* @param waterMarkName 水印字符
*/
public static void stringWaterMark(String filePath, String waterMarkName) {
PdfReader reader = null;
PdfStamper stamper = null;
OutputStream os = null;
try {
reader = new PdfReader(filePath);
os = new FileOutputStream(filePath);
stamper = new PdfStamper(reader, os);
// 添加中文字体
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
int total = reader.getNumberOfPages() + 1;
PdfContentByte under;
int j = waterMarkName.length();
char c = 0;
int rise = 0;
// 给每一页加水印
for (int i = 1; i < total; i++) {
rise = 400;
under = stamper.getUnderContent(i);
under.beginText();
under.setFontAndSize(bfChinese, 30);
under.setTextMatrix(200, 120);
for (int k = 0; k < j; k++) {
under.setTextRise(rise);
c = waterMarkName.charAt(k);
under.showText(c + "");
}
// 添加水印文字
under.endText();
}
stamper.close();
} catch (Exception e) {
LOGGER.error("【PDF】添加水印字符串失败:" + e.getMessage(), e);
} finally {
try {
if (os != null) {
os.close();
}
if (reader != null) {
reader.close();
}
if (stamper != null) {
stamper.close();
}
} catch (Exception e) {
}
}
}
/**
* 加水印(图片)
*
* @param inputFile
* 需要加水印的PDF路径
* @param outputFile
* 输出生成PDF的路径
* @param imageFile
* 水印图片路径
*/
// public static void imageWaterMark(String inputFile, String imageFile) {
// try {
// String[] spe = separatePath(inputFile);
// String outputFile = spe[0] + "_WM." + spe[1];
//
// PdfReader reader = new PdfReader(inputFile);
// PdfStamper stamper = new PdfStamper(reader, new
// FileOutputStream(outputFile));
//
// int total = reader.getNumberOfPages() + 1;
//
// Image image = Image.getInstance(imageFile);
// image.setAbsolutePosition(-100, 0);// 坐标
// image.scaleAbsolute(800, 1000);// 自定义大小
// // image.setRotation(-20);//旋转 弧度
// // image.setRotationDegrees(-45);//旋转 角度
// // image.scalePercent(50);//依照比例缩放
// PdfGState gs = new PdfGState();
// gs.setFillOpacity(0.2f);// 设置透明度为0.2
// PdfContentByte under;
// // 给每一页加水印
// for (int i = 1; i < total; i++) {
// under = stamper.getUnderContent(i);
// under.beginText();
// // 添加水印图片
// under.addImage(image);
// under.setGState(gs);
// }
// stamper.close();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
/**
* 结束关闭文件流
*
* @param document
* @param os
*/
private static void close(Document document, OutputStream os, PdfWriter pdfWriter) {
try {
if (document != null) {
document.close();
document = null;
}
if (os != null) {
os.close();
os = null;
}
if (pdfWriter != null) {
pdfWriter.close();
}
} catch (Exception e) {
LOGGER.error("【PDF】PDF文件流关闭失败:" + e.getMessage(), e);
}
}
}
package com.pcloud.common.utils.pdf;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.google.common.collect.Lists;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
import com.pcloud.common.constant.FilePathConst;
import com.pcloud.common.entity.UploadResultInfo;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.exceptions.FileException;
import com.pcloud.common.utils.FileUtils;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.UUIDUitl;
import com.pcloud.common.utils.aliyun.OssUtils;
import com.pcloud.common.utils.pdf.po.PdfChunkPO;
import com.pcloud.common.utils.pdf.po.PdfImagePO;
import com.pcloud.common.utils.pdf.po.PdfPO;
import com.pcloud.common.utils.pdf.po.PdfTablePO;
import com.pcloud.common.utils.string.StringUtil;
/**
* @author Administrator
*/
@Component("pdfUtils")
public class PdfUtils {
/**
*
*/
private static final Logger LOGGER = LoggerFactory.getLogger(PdfUtils.class);
/**
* PDF转换图片的宽度
*/
public static final Integer IMAGE_WITH = 1654;
/**
* PDF转换图片的高度
*/
public static final Integer IMAGE_HEIGHT = 2399;
/**
* PDF文件转换图片
*
* @param fileUrl
* @param format
* @return
* @throws Exception
*/
@Deprecated
public static List<UploadResultInfo> pdfToImage(String fileUrl, String format) throws FileException {
if (StringUtil.isEmpty(fileUrl))
return null;
if (!StringUtil.isEmpty(fileUrl))
return null;
String fileName = FileUtils.getFileName(fileUrl);
// 下载PDF文件
byte[] bytes = FileUtils.downloadByteFromUrl(fileUrl);
if (bytes == null) {
throw new FileException(FileException.FILE_DOWNLOAD_FAILURE, "下载文件失败");
}
if (bytes.length == 0) {
return Lists.newArrayList();
}
// 解析PDF文件
String outPath = pdfConvert(bytes, fileName, "", format);
// 上传图片文件
return pdfImageUpload(outPath, fileName, format);
}
/**
* PDF转换文件
*
* @param b
* @param fileName
* @param prefix
* @param format
* @return
* @throws Exception
*/
private static String pdfConvert(byte[] b, String fileName, String prefix, String format) throws FileException {
// 解析PDF文件
String outPath = FilePathConst.PDF_PATH + fileName + "_" + UUIDUitl.generateString(12);
File fi = new File(outPath);
if (!fi.exists()) {
fi.mkdirs();
}
try {
// PdfToImage pImage = new PdfToImage(IMAGE_WITH, IMAGE_HEIGHT, prefix, format);
// pImage.convertPagesToHiResImages(b, outPath);
} catch (Exception e) {
FileUtils.deleteDirectory(outPath);
LOGGER.error("【PDF】PDF转换图片失败:" + e.getMessage(), e);
throw new FileException(FileException.FILE_CONTENT_ERROR, "PDF转换图片失败");
}
return outPath;
}
/**
* PDF图片上传
*
* @param outPath
* @param format
* @return
* @throws Exception
*/
private static List<UploadResultInfo> pdfImageUpload(String outPath, String fileName, String format)
throws FileException {
List<UploadResultInfo> list = Lists.newArrayList();
try {
File[] fileArray = new File(outPath).listFiles();
for (int i = 0; i < fileArray.length; i++) {
// modify by songx at 2017-05-19
// PDF工具包生成的图片已pageXXX命名,所以取XXX为文件的页数
String childDileName = FileUtils.getFileName(fileArray[i].getName());
int page = Integer.valueOf(childDileName.replace("page", ""));
UploadResultInfo uploadResultInfo = OssUtils.uploadLocalFile4CustomName(fileArray[i].getPath(),
fileName + "_" + page);
if (uploadResultInfo == null) {
throw new FileException(FileException.FILE_CONTENT_ERROR, "PDF转换图片上传失败:第" + i + "张");
}
uploadResultInfo.setFileName(childDileName);
uploadResultInfo.setFileType(format);
uploadResultInfo.setPage(page);
list.add(uploadResultInfo);
}
} catch (Exception e) {
LOGGER.error("【PDF】PDF转换图片上传失败:" + e.getMessage(), e);
throw new FileException(FileException.FILE_UPLOAD_FAILURE, "PDF转换图片上传失败");
} finally {
FileUtils.deleteDirectory(outPath);
}
return list;
}
/**
* 创建PDF
*
* @param pdfChunkDOs
* @return
* @throws Exception
*/
public static String create(List<PdfPO> pdfPOs) throws FileException {
LOGGER.info("【PDF】创建PDF文档,<START>");
if (ListUtils.isEmpty(pdfPOs)) {
return null;
}
String outPath = null;
PdfWriter pdfWriter = null;
Document document = null;
OutputStream os = null;
try {
// 输出路径
outPath = FilePathConst.PDF_PATH + UUIDUitl.taskName() + ".pdf";
FileUtils.creatFiles(outPath);
// 创建输出流
os = new FileOutputStream(new File(outPath));
// 初始化文档
// 设置纸张
Rectangle rect = new Rectangle(PageSize.A4);
// 创建文档实例
document = new Document(rect, 50, 50, 50, 50);
pdfWriter = PdfWriter.getInstance(document, os);
document.open();
document.newPage();
// 添加内容添加PDF实例中
addChunks(pdfPOs, document);
} catch (Exception e) {
FileUtils.deleteFile(outPath);
LOGGER.error("【PDF】创建PDF文档失败:" + e.getMessage(), e);
throw new FileException(FileException.FILE_CONTENT_ERROR, e.getMessage());
} finally {
close(document, os, pdfWriter);
}
LOGGER.info("【PDF】创建PDF文档,<END>");
return outPath;
}
/**
* 添加内容到PDF中
*
* @param pdfPOs
* @param document
* @throws BizException
* @throws DocumentException
* @throws MalformedURLException
* @throws IOException
*/
private static void addChunks(List<PdfPO> pdfPOs, Document document)
throws BizException, DocumentException, MalformedURLException, IOException {
for (PdfPO pdfPO : pdfPOs) {
if (pdfPO instanceof PdfChunkPO) {
addChunk(pdfPO, document);
} else if (pdfPO instanceof PdfTablePO) {
addTable(pdfPO, document);
} else if (pdfPO instanceof PdfImagePO) {
addImage(pdfPO, document);
}
}
}
/**
* 添加块
*
* @param pdfPO
* @throws BizException
* @throws DocumentException
*/
private static void addChunk(PdfPO pdfPO, Document document) throws BizException, DocumentException {
PdfChunkPO pdfChunkPO = (PdfChunkPO) pdfPO;
// 段落
Paragraph paragraph = null;
Font font = PdfFontUtils.getByType(pdfChunkPO.getPdfFontEnum());
if (pdfChunkPO.isLeanding()) {
paragraph = new Paragraph(pdfChunkPO.getText(), font);
paragraph.setLeading(pdfChunkPO.getLeading() > 0 ? pdfChunkPO.getLeading() : Float.NaN);
} else {
paragraph = new Paragraph();
// 短语
Phrase phrase = new Phrase();
// 短语中的某一块
Chunk chunk = new Chunk(StringUtil.isEmpty(pdfChunkPO.getText()) ? "" : pdfChunkPO.getText(), font);
// skew大于0 的时候生效.字体倾斜角度
if (pdfChunkPO.getSkew() > 0) {
chunk.setSkew(0, pdfChunkPO.getSkew());
}
// 将块添加到短语
phrase.add(chunk);
// 将短语添加到段落
paragraph.add(phrase);
}
// 段落前间距
paragraph.setSpacingBefore(pdfChunkPO.getSpacingBefore() > 0 ? pdfChunkPO.getSpacingBefore() : Float.NaN);
// 段落后间距
paragraph.setSpacingAfter(pdfChunkPO.getSpacingAfter() > 0 ? pdfChunkPO.getSpacingAfter() : Float.NaN);
// 段落位置
paragraph.setAlignment(pdfChunkPO.getPdfAlignEnum().value);
// 将段落添加到文档
document.add(paragraph);
}
/**
* 添加表格
*
* @param pdfPO
* @throws BizException
* @throws DocumentException
*/
private static void addTable(PdfPO pdfPO, Document document) throws BizException, DocumentException {
PdfTablePO pdfTablePO = (PdfTablePO) pdfPO;
String[][] contents = pdfTablePO.getContents();
if (contents == null || contents.length < 1) {
return;
}
int rowNum = contents.length; // 总行数
int colNum = pdfTablePO.getColumnWidths().length; // 总列数
if (colNum < 1) {
throw new FileException(FileException.FILE_CONTENT_ERROR, "表格列数与内容列数不一致");
}
// 字体
Font font = PdfFontUtils.getByType(pdfTablePO.getPdfFontEnum());
// 创建表格
PdfPTable table = new PdfPTable(colNum);
table.setTotalWidth(pdfTablePO.getColumnWidths()); // 设置列宽
table.setLockedWidth(true); // 锁定列宽
// 设置行和列
for (int i = 0; i < rowNum; i++) {
String[] cols = contents[i];
for (int j = 0; j < colNum; j++) {
String text = (j >= cols.length || StringUtil.isEmpty(cols[j])) ? "" : cols[j];
// 填充单元格内容
PdfPCell cell = new PdfPCell(new Phrase(text, font));
// 设置上边的边框宽度
cell.setBorderWidthTop(1);
// 设置左边的边框宽度
cell.setBorderWidthLeft(1);
// 设置右边的边框宽度
if (j == (colNum - 1)) {
cell.setBorderWidthRight(1);
}
// 设置底部的边框宽度
if (i == (rowNum - 1)) {
cell.setBorderWidthBottom(1);
}
// 设置单元格高度
cell.setMinimumHeight(pdfTablePO.getMinimumHeight() > 0 ? pdfTablePO.getMinimumHeight() : Float.NaN);
// 设置可以居中
cell.setUseAscender(true);
// 设置水平居中
cell.setHorizontalAlignment(pdfTablePO.getPdfAlignEnum().value);
// 设置垂直居中
cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
table.addCell(cell);
}
}
// 将表格添加到文档
document.add(table);
}
/**
* 添加图片
*
* @param pdfPO
* @param document
* @throws MalformedURLException
* @throws IOException
* @throws DocumentException
*/
private static void addImage(PdfPO pdfPO, Document document)
throws MalformedURLException, IOException, DocumentException {
PdfImagePO pdfImagePO = (PdfImagePO) pdfPO;
Image image = null;
if (!StringUtil.isEmpty(pdfImagePO.getImageUrl())) {
if (pdfImagePO.getImageUrl().startsWith("http")) {
image = Image.getInstance(new URL(pdfImagePO.getImageUrl()));
} else {
image = Image.getInstance(pdfImagePO.getImageUrl());
}
image.setAlignment(pdfImagePO.getPdfAlignEnum().value);
if (pdfImagePO.getHeight() > 0 || pdfImagePO.getWidth() > 0) {
image.scaleAbsolute(pdfImagePO.getHeight(), pdfImagePO.getWidth());
}
} else if (pdfImagePO.getImageByte() != null) {
image = Image.getInstance(pdfImagePO.getImageByte());
} else {
return;
}
// 将表格添加到文档
document.add(image);
}
/**
* 加水印(字符串)
*
* @param inputFile
* 需要加水印的PDF路径
* @param outputFile
* 输出生成PDF的路径
* @param waterMarkName
* 水印字符
*/
public static void stringWaterMark(String filePath, String waterMarkName) {
PdfReader reader = null;
PdfStamper stamper = null;
OutputStream os = null;
try {
reader = new PdfReader(filePath);
os = new FileOutputStream(filePath);
stamper = new PdfStamper(reader, os);
// 添加中文字体
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
int total = reader.getNumberOfPages() + 1;
PdfContentByte under;
int j = waterMarkName.length();
char c = 0;
int rise = 0;
// 给每一页加水印
for (int i = 1; i < total; i++) {
rise = 400;
under = stamper.getUnderContent(i);
under.beginText();
under.setFontAndSize(bfChinese, 30);
under.setTextMatrix(200, 120);
for (int k = 0; k < j; k++) {
under.setTextRise(rise);
c = waterMarkName.charAt(k);
under.showText(c + "");
}
// 添加水印文字
under.endText();
}
stamper.close();
} catch (Exception e) {
LOGGER.error("【PDF】添加水印字符串失败:" + e.getMessage(), e);
} finally {
try {
if (os != null) {
os.close();
}
if (reader != null) {
reader.close();
}
if (stamper != null) {
stamper.close();
}
} catch (Exception e) {
}
}
}
/**
* 加水印(图片)
*
* @param inputFile
* 需要加水印的PDF路径
* @param outputFile
* 输出生成PDF的路径
* @param imageFile
* 水印图片路径
*/
// public static void imageWaterMark(String inputFile, String imageFile) {
// try {
// String[] spe = separatePath(inputFile);
// String outputFile = spe[0] + "_WM." + spe[1];
//
// PdfReader reader = new PdfReader(inputFile);
// PdfStamper stamper = new PdfStamper(reader, new
// FileOutputStream(outputFile));
//
// int total = reader.getNumberOfPages() + 1;
//
// Image image = Image.getInstance(imageFile);
// image.setAbsolutePosition(-100, 0);// 坐标
// image.scaleAbsolute(800, 1000);// 自定义大小
// // image.setRotation(-20);//旋转 弧度
// // image.setRotationDegrees(-45);//旋转 角度
// // image.scalePercent(50);//依照比例缩放
// PdfGState gs = new PdfGState();
// gs.setFillOpacity(0.2f);// 设置透明度为0.2
// PdfContentByte under;
// // 给每一页加水印
// for (int i = 1; i < total; i++) {
// under = stamper.getUnderContent(i);
// under.beginText();
// // 添加水印图片
// under.addImage(image);
// under.setGState(gs);
// }
// stamper.close();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
/**
* 结束关闭文件流
*
* @param document
* @param os
*/
private static void close(Document document, OutputStream os, PdfWriter pdfWriter) {
try {
if (document != null) {
document.close();
document = null;
}
if (os != null) {
os.close();
os = null;
}
if (pdfWriter != null) {
pdfWriter.close();
}
} catch (Exception e) {
LOGGER.error("【PDF】PDF文件流关闭失败:" + e.getMessage(), e);
}
}
}
......@@ -233,14 +233,6 @@
</dependency>
<!-- Common Dependency End -->
<!-- Mysql Driver Begin -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
<!-- Mysql Driver End -->
<!-- logback-json -->
<dependency>
<groupId>ch.qos.logback.contrib</groupId>
......@@ -258,18 +250,14 @@
<version>0.1.2</version>
</dependency>
<!-- Others Begin -->
<dependency>
<groupId>org.jboss.netty</groupId>
<artifactId>netty</artifactId>
<version>3.2.10.Final</version>
</dependency>
<!-- Mysql Driver Begin -->
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
<version>5.15.0</version>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
<!-- Others End -->
<!-- Mysql Driver End -->
<!-- 图片处理工具 added by songx at 2017-05-17 -->
<dependency>
......@@ -297,13 +285,6 @@
<version>3.0.0</version>
</dependency>
<!-- PDF解析工具 added by songx at 2017-06-13 -->
<dependency>
<groupId>pcloud.tools</groupId>
<artifactId>tools</artifactId>
<version>18.03.22</version>
</dependency>
<!-- 阿里云媒体转码SDK包 added by songx at 2017-06-22 -->
<dependency>
<groupId>com.aliyun</groupId>
......@@ -320,6 +301,7 @@
<artifactId>aliyun-java-sdk-mts</artifactId>
<version>2.1.7</version>
</dependency>
<!-- end -->
<!-- solr add by gaop at 2018-4-23 11:33:47 -->
<dependency>
......@@ -327,7 +309,6 @@
<artifactId>spring-data-solr</artifactId>
<version>${spring.data.solr.version}</version>
</dependency>
<!-- end -->
<!-- Jackson Begin -->
<dependency>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment