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" <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"> 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> <modelVersion>4.0.0</modelVersion>
<parent> <parent>
<groupId>com.pcloud.common</groupId> <groupId>com.pcloud.common</groupId>
<artifactId>pcloud-common-parent</artifactId> <artifactId>pcloud-common-parent</artifactId>
<version>2.1.0-RELEASE</version> <version>2.1.0-RELEASE</version>
</parent> </parent>
<artifactId>pcloud-common-core</artifactId> <artifactId>pcloud-common-core</artifactId>
<packaging>jar</packaging> <packaging>jar</packaging>
<version>${pcloud-common-core.version}</version> <version>${pcloud-common-core.version}</version>
<name>pcloud-common-core</name> <name>pcloud-common-core</name>
<url>http://maven.apache.org</url> <url>http://maven.apache.org</url>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> </properties>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>com.pcloud.common</groupId> <groupId>com.pcloud.common</groupId>
<artifactId>pcloud-common</artifactId> <artifactId>pcloud-common</artifactId>
<version>${pcloud-common.version}</version> <version>${pcloud-common.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<!-- Database connect Begin --> <!-- Database connect Begin -->
<dependency> <dependency>
<groupId>com.alibaba</groupId> <groupId>com.alibaba</groupId>
<artifactId>druid</artifactId> <artifactId>druid</artifactId>
</dependency> </dependency>
<!-- Database connect End --> <!-- Database connect End -->
<!-- Mysql Driver Begin --> <!-- Mysql Driver Begin -->
<dependency> <dependency>
<groupId>mysql</groupId> <groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId> <artifactId>mysql-connector-java</artifactId>
</dependency> </dependency>
<!-- Mysql Driver End --> <!-- Mysql Driver End -->
<!-- ActiveMq Begin --> <!-- Jackson Begin -->
<dependency> <dependency>
<groupId>org.apache.activemq</groupId> <groupId>org.codehaus.jackson</groupId>
<artifactId>activemq-all</artifactId> <artifactId>jackson-mapper-asl</artifactId>
</dependency> </dependency>
<!-- ActiveMq End --> <!-- Jackson End -->
</dependencies>
<!-- Jackson Begin -->
<dependency> </project>
<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>
/** /**
* *
*/ */
package com.pcloud.common.core.constant; package com.pcloud.common.core.constant;
/** /**
*
*
* @author:songx * @author:songx
* @date:2017年2月27日,下午4:29:06 * @date:2017年2月27日,下午4:29:06 使用RabbitMQ需要去MqQueueConstant中声明队列名称,枚举的第二个值将不再使用,第一个值正常使用
*
* 使用RabbitMQ需要去MqQueueConstant中声明队列名称,枚举的第二个值将不再使用,第一个值正常使用
* modify by songx at 2018-08-22 * modify by songx at 2018-08-22
*/ */
public enum ConvertEnum { public enum ConvertEnum {
/** /**
* 应用转码 * 应用转码
*/ */
APP("APP", "convert2App"), APP("APP"),
/** /**
* 资源中心转码 * 资源中心转码
*/ */
RESOURCE("RESOURCE", "convert2Resource"), RESOURCE("RESOURCE"),
/** /**
* 报名时的视频转换 * 报名时的视频转换
*/ */
MATCH("MATCH", "convert2Resource"), MATCH("MATCH"),
/** /**
* 资源中心即时转换 * 资源中心即时转换
*/ */
INSTANT_RESOURCE("INSTANT_RESOURCE", "convert2Resource"), INSTANT_RESOURCE("INSTANT_RESOURCE"),
/** /**
* 报名应用 * 报名应用
*/ */
MATCH_APP("MATCH_APP", "convert2MatchApp"), MATCH_APP("MATCH_APP"),
/** /**
* 内容中心 * 内容中心
*/ */
CONTENT("CONTENT", "convert2Content"), CONTENT("CONTENT"),
/** /**
* 内容中心->题库:文件记忆功能 * 内容中心->题库:文件记忆功能
*/ */
PRETEST_FILEMEMORY("PRETEST_FILEMEMORY", "convert2PretestFilememory"), PRETEST_FILEMEMORY("PRETEST_FILEMEMORY"),
/** /**
* 小游戏 * 小游戏
*/ */
RAYSTASK("RAYSTASK", "convert2Raystask"), RAYSTASK("RAYSTASK"),
/** /**
* 圈子应用 * 圈子应用
*/ */
GROUP_APP("GROUP_APP", "convert2GroupApp"), GROUP_APP("GROUP_APP"),
/** /**
* 投票应用 * 投票应用
*/ */
VOTE_APP("VOTE_APP", "convert2VoteApp"), VOTE_APP("VOTE_APP"),
/** /**
* 教育表格应用 * 教育表格应用
*/ */
EF_APP("EF_APP", "convert2EfApp"), EF_APP("EF_APP"),
/** /**
* 测试工具 * 测试工具
*/ */
TEST_APP("TEST_APP", "convert2TestApp"), TEST_APP("TEST_APP"),
/** /**
* 直播工具 * 直播工具
*/ */
LIVE_APP("LIVE_APP", "convert2LiveApp"), LIVE_APP("LIVE_APP"),
/** /**
* 视频课 * 视频课
*/ */
VIDEO_LESSON("VIDEO_LESSON", "convert2VideoLesson"), 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 value;
/** /**
* 模板名称 * 构造
*/ *
public final String jmsTemplate; * @param value
*/
/** private ConvertEnum(String value) {
* 构造 this.value = value;
* }
* @param value
*/
private ConvertEnum(String value, String jmsTemplate) {
this.value = value;
this.jmsTemplate = jmsTemplate;
}
} }
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 @@ ...@@ -203,6 +203,13 @@
</dependency> </dependency>
<!-- sftp end --> <!-- sftp end -->
<!-- google Begin -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<!-- google End -->
<!-- ftp begin --> <!-- ftp begin -->
<dependency> <dependency>
<groupId>commons-net</groupId> <groupId>commons-net</groupId>
...@@ -241,12 +248,6 @@ ...@@ -241,12 +248,6 @@
<artifactId>freemarker</artifactId> <artifactId>freemarker</artifactId>
</dependency> </dependency>
<!-- PDF解析工具 -->
<dependency>
<groupId>pcloud.tools</groupId>
<artifactId>tools</artifactId>
</dependency>
<!-- 图片处理工具 added by songx at 2017-05-17 --> <!-- 图片处理工具 added by songx at 2017-05-17 -->
<dependency> <dependency>
<groupId>net.coobird</groupId> <groupId>net.coobird</groupId>
...@@ -297,12 +298,6 @@ ...@@ -297,12 +298,6 @@
</dependency> </dependency>
<!-- end --> <!-- end -->
<!-- google 工具包 -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<!-- Jackson Begin --> <!-- Jackson Begin -->
<dependency> <dependency>
<groupId>org.codehaus.jackson</groupId> <groupId>org.codehaus.jackson</groupId>
...@@ -378,12 +373,7 @@ ...@@ -378,12 +373,7 @@
<version>1.5.2</version> <version>1.5.2</version>
</dependency> </dependency>
<!--PDF转图片 -->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.9</version>
</dependency>
<dependency> <dependency>
<groupId>com.github.jai-imageio</groupId> <groupId>com.github.jai-imageio</groupId>
......
package com.pcloud.common.utils.pdf; package com.pcloud.common.utils.pdf;
import java.awt.image.BufferedImage; import java.io.File;
import java.io.File; import java.io.FileOutputStream;
import java.io.FileOutputStream; import java.io.IOException;
import java.io.IOException; import java.io.OutputStream;
import java.io.OutputStream; import java.net.MalformedURLException;
import java.net.MalformedURLException; import java.net.URL;
import java.net.URL; import java.util.List;
import java.util.List;
import org.slf4j.Logger;
import org.apache.pdfbox.pdmodel.PDDocument; import org.slf4j.LoggerFactory;
import org.apache.pdfbox.rendering.PDFRenderer; import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import com.google.common.collect.Lists;
import org.springframework.stereotype.Component; import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.google.common.collect.Lists; import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Chunk; import com.itextpdf.text.Font;
import com.itextpdf.text.Document; import com.itextpdf.text.Image;
import com.itextpdf.text.DocumentException; import com.itextpdf.text.PageSize;
import com.itextpdf.text.Font; import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Image; import com.itextpdf.text.Phrase;
import com.itextpdf.text.PageSize; import com.itextpdf.text.Rectangle;
import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.Phrase; import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.BaseFont; import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.PdfReader; import com.pcloud.common.constant.FilePathConst;
import com.itextpdf.text.pdf.PdfStamper; import com.pcloud.common.entity.UploadResultInfo;
import com.itextpdf.text.pdf.PdfWriter; import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.constant.FilePathConst; import com.pcloud.common.exceptions.FileException;
import com.pcloud.common.entity.UploadResultInfo; import com.pcloud.common.utils.FileUtils;
import com.pcloud.common.exceptions.BizException; import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.exceptions.FileException; import com.pcloud.common.utils.UUIDUitl;
import com.pcloud.common.utils.FileUtils; import com.pcloud.common.utils.aliyun.OssUtils;
import com.pcloud.common.utils.ListUtils; import com.pcloud.common.utils.pdf.po.PdfChunkPO;
import com.pcloud.common.utils.UUIDUitl; import com.pcloud.common.utils.pdf.po.PdfImagePO;
import com.pcloud.common.utils.aliyun.OssUtils; import com.pcloud.common.utils.pdf.po.PdfPO;
import com.pcloud.common.utils.pdf.po.PdfChunkPO; import com.pcloud.common.utils.pdf.po.PdfTablePO;
import com.pcloud.common.utils.pdf.po.PdfImagePO; import com.pcloud.common.utils.string.StringUtil;
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
import com.pcloud.tools.pdf.convert.image.PdfToImage; */
@Component("pdfUtils")
import javax.imageio.ImageIO; public class PdfUtils {
/** /**
* @author Administrator *
*/ */
@Component("pdfUtils") private static final Logger LOGGER = LoggerFactory.getLogger(PdfUtils.class);
public class PdfUtils {
/**
/** * PDF转换图片的宽度
* */
*/ public static final Integer IMAGE_WITH = 1654;
private static final Logger LOGGER = LoggerFactory.getLogger(PdfUtils.class);
/**
/** * PDF转换图片的高度
* PDF转换图片的宽度 */
*/ public static final Integer IMAGE_HEIGHT = 2399;
public static final Integer IMAGE_WITH = 1654;
/**
/** * PDF文件转换图片
* PDF转换图片的高度 *
*/ * @param fileUrl
public static final Integer IMAGE_HEIGHT = 2399; * @param format
* @return
/** * @throws Exception
* PDF文件转换图片 */
* @Deprecated
* @param fileUrl public static List<UploadResultInfo> pdfToImage(String fileUrl, String format) throws FileException {
* @param format if (StringUtil.isEmpty(fileUrl))
* @return return null;
* @throws Exception if (!StringUtil.isEmpty(fileUrl))
*/ return null;
public static List<UploadResultInfo> pdfToImage(String fileUrl, String format) throws FileException { String fileName = FileUtils.getFileName(fileUrl);
String fileName = FileUtils.getFileName(fileUrl); // 下载PDF文件
// 下载PDF文件 byte[] bytes = FileUtils.downloadByteFromUrl(fileUrl);
byte[] bytes = FileUtils.downloadByteFromUrl(fileUrl); if (bytes == null) {
if (bytes == null) { throw new FileException(FileException.FILE_DOWNLOAD_FAILURE, "下载文件失败");
throw new FileException(FileException.FILE_DOWNLOAD_FAILURE, "下载文件失败"); }
} if (bytes.length == 0) {
if (bytes.length == 0) { return Lists.newArrayList();
return Lists.newArrayList(); }
} // 解析PDF文件
// 解析PDF文件 String outPath = pdfConvert(bytes, fileName, "", format);
String outPath = pdfConvert(bytes, fileName, "", format); // 上传图片文件
// 上传图片文件 return pdfImageUpload(outPath, fileName, format);
return pdfImageUpload(outPath, fileName, format); }
}
/**
/** * PDF转换文件
* PDF文件转换图片 *
* * @param b
* @param fileUrl * @param fileName
* @param format * @param prefix
* @return * @param format
*/ * @return
public static List<UploadResultInfo> pdf2Image(String fileUrl, String format) { * @throws Exception
String fileName = FileUtils.getFileName(fileUrl); */
String filePath = FilePathConst.DOWNLOAD_PATH + fileName + "_" + UUIDUitl.generateString(12); private static String pdfConvert(byte[] b, String fileName, String prefix, String format) throws FileException {
String outputPath = FilePathConst.PDF_PATH + fileName + "_" + UUIDUitl.generateString(12); // 解析PDF文件
try { String outPath = FilePathConst.PDF_PATH + fileName + "_" + UUIDUitl.generateString(12);
FileUtils.downloadFileFromUrl(fileUrl, filePath); File fi = new File(outPath);
File outputDir = new File(outputPath); if (!fi.exists()) {
if (!outputDir.exists()) { fi.mkdirs();
outputDir.mkdir(); }
} try {
File file = new File(filePath); // PdfToImage pImage = new PdfToImage(IMAGE_WITH, IMAGE_HEIGHT, prefix, format);
if (!file.exists()) { // pImage.convertPagesToHiResImages(b, outPath);
LOGGER.error(fileUrl + " download error"); } catch (Exception e) {
throw new FileException(FileException.FILE_DOWNLOAD_FAILURE, "下载文件失败"); FileUtils.deleteDirectory(outPath);
} LOGGER.error("【PDF】PDF转换图片失败:" + e.getMessage(), e);
LOGGER.info("pdf downloaded to Folder: " + outputDir.getName()); throw new FileException(FileException.FILE_CONTENT_ERROR, "PDF转换图片失败");
PDDocument document = PDDocument.load(new File(filePath)); }
int total = document.getNumberOfPages(); return outPath;
LOGGER.info("Total images to be converted: " + total); }
PDFRenderer render = new PDFRenderer(document);
/**
for (int i = 0; i < total; i++) { * PDF图片上传
BufferedImage image = render.renderImage(i, 2.0f); *
File outputfile = new File(outputPath + "page" + (i + 1) + "." + format); * @param outPath
ImageIO.write(image, format, outputfile); * @param format
} * @return
document.close(); * @throws Exception
LOGGER.info("Converted Images are saved at: " + outputDir.getAbsolutePath()); */
return pdfImageUpload(outputPath, fileName, format); private static List<UploadResultInfo> pdfImageUpload(String outPath, String fileName, String format)
} catch (Exception e) { throws FileException {
LOGGER.warn("pdf convert error", e); List<UploadResultInfo> list = Lists.newArrayList();
return pdfToImage(fileUrl, format); 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为文件的页数
* PDF转换文件 String childDileName = FileUtils.getFileName(fileArray[i].getName());
* int page = Integer.valueOf(childDileName.replace("page", ""));
* @param b UploadResultInfo uploadResultInfo = OssUtils.uploadLocalFile4CustomName(fileArray[i].getPath(),
* @param fileName fileName + "_" + page);
* @param prefix if (uploadResultInfo == null) {
* @param format throw new FileException(FileException.FILE_CONTENT_ERROR, "PDF转换图片上传失败:第" + i + "张");
* @return }
* @throws Exception uploadResultInfo.setFileName(childDileName);
*/ uploadResultInfo.setFileType(format);
private static String pdfConvert(byte[] b, String fileName, String prefix, String format) throws FileException { uploadResultInfo.setPage(page);
// 解析PDF文件 list.add(uploadResultInfo);
String outPath = FilePathConst.PDF_PATH + fileName + "_" + UUIDUitl.generateString(12); }
File fi = new File(outPath); } catch (Exception e) {
if (!fi.exists()) { LOGGER.error("【PDF】PDF转换图片上传失败:" + e.getMessage(), e);
fi.mkdirs(); throw new FileException(FileException.FILE_UPLOAD_FAILURE, "PDF转换图片上传失败");
} } finally {
try { FileUtils.deleteDirectory(outPath);
PdfToImage pImage = new PdfToImage(IMAGE_WITH, IMAGE_HEIGHT, prefix, format); }
pImage.convertPagesToHiResImages(b, outPath); return list;
} catch (Exception e) { }
FileUtils.deleteDirectory(outPath);
LOGGER.error("【PDF】PDF转换图片失败:" + e.getMessage(), e); /**
throw new FileException(FileException.FILE_CONTENT_ERROR, "PDF转换图片失败"); * 创建PDF
} *
return outPath; * @param pdfChunkDOs
} * @return
* @throws Exception
/** */
* PDF图片上传 public static String create(List<PdfPO> pdfPOs) throws FileException {
* LOGGER.info("【PDF】创建PDF文档,<START>");
* @param outPath if (ListUtils.isEmpty(pdfPOs)) {
* @param format return null;
* @return }
* @throws Exception String outPath = null;
*/ PdfWriter pdfWriter = null;
private static List<UploadResultInfo> pdfImageUpload(String outPath, String fileName, String format) Document document = null;
throws FileException { OutputStream os = null;
List<UploadResultInfo> list = Lists.newArrayList(); try {
try { // 输出路径
File[] fileArray = new File(outPath).listFiles(); outPath = FilePathConst.PDF_PATH + UUIDUitl.taskName() + ".pdf";
for (int i = 0; i < fileArray.length; i++) { FileUtils.creatFiles(outPath);
// modify by songx at 2017-05-19 // 创建输出流
// PDF工具包生成的图片已pageXXX命名,所以取XXX为文件的页数 os = new FileOutputStream(new File(outPath));
String childDileName = FileUtils.getFileName(fileArray[i].getName()); // 初始化文档
int page = Integer.valueOf(childDileName.replace("page", "")); // 设置纸张
UploadResultInfo uploadResultInfo = OssUtils.uploadLocalFile4CustomName(fileArray[i].getPath(), Rectangle rect = new Rectangle(PageSize.A4);
fileName + "_" + page); // 创建文档实例
if (uploadResultInfo == null) { document = new Document(rect, 50, 50, 50, 50);
throw new FileException(FileException.FILE_CONTENT_ERROR, "PDF转换图片上传失败:第" + i + "张"); pdfWriter = PdfWriter.getInstance(document, os);
} document.open();
uploadResultInfo.setFileName(childDileName); document.newPage();
uploadResultInfo.setFileType(format); // 添加内容添加PDF实例中
uploadResultInfo.setPage(page); addChunks(pdfPOs, document);
list.add(uploadResultInfo); } catch (Exception e) {
} FileUtils.deleteFile(outPath);
} catch (Exception e) { LOGGER.error("【PDF】创建PDF文档失败:" + e.getMessage(), e);
LOGGER.error("【PDF】PDF转换图片上传失败:" + e.getMessage(), e); throw new FileException(FileException.FILE_CONTENT_ERROR, e.getMessage());
throw new FileException(FileException.FILE_UPLOAD_FAILURE, "PDF转换图片上传失败"); } finally {
} finally { close(document, os, pdfWriter);
FileUtils.deleteDirectory(outPath); }
} LOGGER.info("【PDF】创建PDF文档,<END>");
return list; return outPath;
} }
/** /**
* 创建PDF * 添加内容到PDF中
* *
* @param pdfChunkDOs * @param pdfPOs
* @return * @param document
* @throws Exception * @throws BizException
*/ * @throws DocumentException
public static String create(List<PdfPO> pdfPOs) throws FileException { * @throws MalformedURLException
LOGGER.info("【PDF】创建PDF文档,<START>"); * @throws IOException
if (ListUtils.isEmpty(pdfPOs)) { */
return null; private static void addChunks(List<PdfPO> pdfPOs, Document document)
} throws BizException, DocumentException, MalformedURLException, IOException {
String outPath = null; for (PdfPO pdfPO : pdfPOs) {
PdfWriter pdfWriter = null; if (pdfPO instanceof PdfChunkPO) {
Document document = null; addChunk(pdfPO, document);
OutputStream os = null; } else if (pdfPO instanceof PdfTablePO) {
try { addTable(pdfPO, document);
// 输出路径 } else if (pdfPO instanceof PdfImagePO) {
outPath = FilePathConst.PDF_PATH + UUIDUitl.taskName() + ".pdf"; addImage(pdfPO, document);
FileUtils.creatFiles(outPath); }
// 创建输出流 }
os = new FileOutputStream(new File(outPath)); }
// 初始化文档
// 设置纸张 /**
Rectangle rect = new Rectangle(PageSize.A4); * 添加块
// 创建文档实例 *
document = new Document(rect, 50, 50, 50, 50); * @param pdfPO
pdfWriter = PdfWriter.getInstance(document, os); * @throws BizException
document.open(); * @throws DocumentException
document.newPage(); */
// 添加内容添加PDF实例中 private static void addChunk(PdfPO pdfPO, Document document) throws BizException, DocumentException {
addChunks(pdfPOs, document); PdfChunkPO pdfChunkPO = (PdfChunkPO) pdfPO;
} catch (Exception e) { // 段落
FileUtils.deleteFile(outPath); Paragraph paragraph = null;
LOGGER.error("【PDF】创建PDF文档失败:" + e.getMessage(), e); Font font = PdfFontUtils.getByType(pdfChunkPO.getPdfFontEnum());
throw new FileException(FileException.FILE_CONTENT_ERROR, e.getMessage()); if (pdfChunkPO.isLeanding()) {
} finally { paragraph = new Paragraph(pdfChunkPO.getText(), font);
close(document, os, pdfWriter); paragraph.setLeading(pdfChunkPO.getLeading() > 0 ? pdfChunkPO.getLeading() : Float.NaN);
} } else {
LOGGER.info("【PDF】创建PDF文档,<END>"); paragraph = new Paragraph();
return outPath; // 短语
} Phrase phrase = new Phrase();
// 短语中的某一块
/** Chunk chunk = new Chunk(StringUtil.isEmpty(pdfChunkPO.getText()) ? "" : pdfChunkPO.getText(), font);
* 添加内容到PDF中 // skew大于0 的时候生效.字体倾斜角度
* if (pdfChunkPO.getSkew() > 0) {
* @param pdfPOs chunk.setSkew(0, pdfChunkPO.getSkew());
* @param document }
* @throws BizException // 将块添加到短语
* @throws DocumentException phrase.add(chunk);
* @throws MalformedURLException // 将短语添加到段落
* @throws IOException paragraph.add(phrase);
*/ }
private static void addChunks(List<PdfPO> pdfPOs, Document document) // 段落前间距
throws BizException, DocumentException, MalformedURLException, IOException { paragraph.setSpacingBefore(pdfChunkPO.getSpacingBefore() > 0 ? pdfChunkPO.getSpacingBefore() : Float.NaN);
for (PdfPO pdfPO : pdfPOs) { // 段落后间距
if (pdfPO instanceof PdfChunkPO) { paragraph.setSpacingAfter(pdfChunkPO.getSpacingAfter() > 0 ? pdfChunkPO.getSpacingAfter() : Float.NaN);
addChunk(pdfPO, document); // 段落位置
} else if (pdfPO instanceof PdfTablePO) { paragraph.setAlignment(pdfChunkPO.getPdfAlignEnum().value);
addTable(pdfPO, document); // 将段落添加到文档
} else if (pdfPO instanceof PdfImagePO) { document.add(paragraph);
addImage(pdfPO, document);
} }
}
} /**
* 添加表格
/** *
* 添加块 * @param pdfPO
* * @throws BizException
* @param pdfPO * @throws DocumentException
* @throws BizException */
* @throws DocumentException private static void addTable(PdfPO pdfPO, Document document) throws BizException, DocumentException {
*/ PdfTablePO pdfTablePO = (PdfTablePO) pdfPO;
private static void addChunk(PdfPO pdfPO, Document document) throws BizException, DocumentException { String[][] contents = pdfTablePO.getContents();
PdfChunkPO pdfChunkPO = (PdfChunkPO) pdfPO; if (contents == null || contents.length < 1) {
// 段落 return;
Paragraph paragraph = null; }
Font font = PdfFontUtils.getByType(pdfChunkPO.getPdfFontEnum()); int rowNum = contents.length; // 总行数
if (pdfChunkPO.isLeanding()) { int colNum = pdfTablePO.getColumnWidths().length; // 总列数
paragraph = new Paragraph(pdfChunkPO.getText(), font); if (colNum < 1) {
paragraph.setLeading(pdfChunkPO.getLeading() > 0 ? pdfChunkPO.getLeading() : Float.NaN); throw new FileException(FileException.FILE_CONTENT_ERROR, "表格列数与内容列数不一致");
} else { }
paragraph = new Paragraph(); // 字体
// 短语 Font font = PdfFontUtils.getByType(pdfTablePO.getPdfFontEnum());
Phrase phrase = new Phrase(); // 创建表格
// 短语中的某一块 PdfPTable table = new PdfPTable(colNum);
Chunk chunk = new Chunk(StringUtil.isEmpty(pdfChunkPO.getText()) ? "" : pdfChunkPO.getText(), font); table.setTotalWidth(pdfTablePO.getColumnWidths()); // 设置列宽
// skew大于0 的时候生效.字体倾斜角度 table.setLockedWidth(true); // 锁定列宽
if (pdfChunkPO.getSkew() > 0) { // 设置行和列
chunk.setSkew(0, pdfChunkPO.getSkew()); for (int i = 0; i < rowNum; i++) {
} String[] cols = contents[i];
// 将块添加到短语 for (int j = 0; j < colNum; j++) {
phrase.add(chunk); String text = (j >= cols.length || StringUtil.isEmpty(cols[j])) ? "" : cols[j];
// 将短语添加到段落 // 填充单元格内容
paragraph.add(phrase); PdfPCell cell = new PdfPCell(new Phrase(text, font));
} // 设置上边的边框宽度
// 段落前间距 cell.setBorderWidthTop(1);
paragraph.setSpacingBefore(pdfChunkPO.getSpacingBefore() > 0 ? pdfChunkPO.getSpacingBefore() : Float.NaN); // 设置左边的边框宽度
// 段落后间距 cell.setBorderWidthLeft(1);
paragraph.setSpacingAfter(pdfChunkPO.getSpacingAfter() > 0 ? pdfChunkPO.getSpacingAfter() : Float.NaN); // 设置右边的边框宽度
// 段落位置 if (j == (colNum - 1)) {
paragraph.setAlignment(pdfChunkPO.getPdfAlignEnum().value); cell.setBorderWidthRight(1);
// 将段落添加到文档 }
document.add(paragraph); // 设置底部的边框宽度
if (i == (rowNum - 1)) {
} cell.setBorderWidthBottom(1);
}
/** // 设置单元格高度
* 添加表格 cell.setMinimumHeight(pdfTablePO.getMinimumHeight() > 0 ? pdfTablePO.getMinimumHeight() : Float.NaN);
* // 设置可以居中
* @param pdfPO cell.setUseAscender(true);
* @throws BizException // 设置水平居中
* @throws DocumentException cell.setHorizontalAlignment(pdfTablePO.getPdfAlignEnum().value);
*/ // 设置垂直居中
private static void addTable(PdfPO pdfPO, Document document) throws BizException, DocumentException { cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
PdfTablePO pdfTablePO = (PdfTablePO) pdfPO; table.addCell(cell);
String[][] contents = pdfTablePO.getContents(); }
if (contents == null || contents.length < 1) { }
return; // 将表格添加到文档
} document.add(table);
int rowNum = contents.length; // 总行数 }
int colNum = pdfTablePO.getColumnWidths().length; // 总列数
if (colNum < 1) { /**
throw new FileException(FileException.FILE_CONTENT_ERROR, "表格列数与内容列数不一致"); * 添加图片
} *
// 字体 * @param pdfPO
Font font = PdfFontUtils.getByType(pdfTablePO.getPdfFontEnum()); * @param document
// 创建表格 * @throws MalformedURLException
PdfPTable table = new PdfPTable(colNum); * @throws IOException
table.setTotalWidth(pdfTablePO.getColumnWidths()); // 设置列宽 * @throws DocumentException
table.setLockedWidth(true); // 锁定列宽 */
// 设置行和列 private static void addImage(PdfPO pdfPO, Document document)
for (int i = 0; i < rowNum; i++) { throws MalformedURLException, IOException, DocumentException {
String[] cols = contents[i]; PdfImagePO pdfImagePO = (PdfImagePO) pdfPO;
for (int j = 0; j < colNum; j++) { Image image = null;
String text = (j >= cols.length || StringUtil.isEmpty(cols[j])) ? "" : cols[j]; if (!StringUtil.isEmpty(pdfImagePO.getImageUrl())) {
// 填充单元格内容 if (pdfImagePO.getImageUrl().startsWith("http")) {
PdfPCell cell = new PdfPCell(new Phrase(text, font)); image = Image.getInstance(new URL(pdfImagePO.getImageUrl()));
// 设置上边的边框宽度 } else {
cell.setBorderWidthTop(1); image = Image.getInstance(pdfImagePO.getImageUrl());
// 设置左边的边框宽度 }
cell.setBorderWidthLeft(1); image.setAlignment(pdfImagePO.getPdfAlignEnum().value);
// 设置右边的边框宽度 if (pdfImagePO.getHeight() > 0 || pdfImagePO.getWidth() > 0) {
if (j == (colNum - 1)) { image.scaleAbsolute(pdfImagePO.getHeight(), pdfImagePO.getWidth());
cell.setBorderWidthRight(1); }
} } else if (pdfImagePO.getImageByte() != null) {
// 设置底部的边框宽度 image = Image.getInstance(pdfImagePO.getImageByte());
if (i == (rowNum - 1)) { } else {
cell.setBorderWidthBottom(1); return;
} }
// 设置单元格高度 // 将表格添加到文档
cell.setMinimumHeight(pdfTablePO.getMinimumHeight() > 0 ? pdfTablePO.getMinimumHeight() : Float.NaN); document.add(image);
// 设置可以居中 }
cell.setUseAscender(true);
// 设置水平居中 /**
cell.setHorizontalAlignment(pdfTablePO.getPdfAlignEnum().value); * 加水印(字符串)
// 设置垂直居中 *
cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); * @param inputFile
table.addCell(cell); * 需要加水印的PDF路径
} * @param outputFile
} * 输出生成PDF的路径
// 将表格添加到文档 * @param waterMarkName
document.add(table); * 水印字符
} */
public static void stringWaterMark(String filePath, String waterMarkName) {
/** PdfReader reader = null;
* 添加图片 PdfStamper stamper = null;
* OutputStream os = null;
* @param pdfPO try {
* @param document reader = new PdfReader(filePath);
* @throws MalformedURLException os = new FileOutputStream(filePath);
* @throws IOException stamper = new PdfStamper(reader, os);
* @throws DocumentException // 添加中文字体
*/ BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
private static void addImage(PdfPO pdfPO, Document document) int total = reader.getNumberOfPages() + 1;
throws MalformedURLException, IOException, DocumentException {
PdfImagePO pdfImagePO = (PdfImagePO) pdfPO; PdfContentByte under;
Image image = null; int j = waterMarkName.length();
if (!StringUtil.isEmpty(pdfImagePO.getImageUrl())) { char c = 0;
if (pdfImagePO.getImageUrl().startsWith("http")) { int rise = 0;
image = Image.getInstance(new URL(pdfImagePO.getImageUrl())); // 给每一页加水印
} else { for (int i = 1; i < total; i++) {
image = Image.getInstance(pdfImagePO.getImageUrl()); rise = 400;
} under = stamper.getUnderContent(i);
image.setAlignment(pdfImagePO.getPdfAlignEnum().value); under.beginText();
if (pdfImagePO.getHeight() > 0 || pdfImagePO.getWidth() > 0) { under.setFontAndSize(bfChinese, 30);
image.scaleAbsolute(pdfImagePO.getHeight(), pdfImagePO.getWidth()); under.setTextMatrix(200, 120);
} for (int k = 0; k < j; k++) {
} else if (pdfImagePO.getImageByte() != null) { under.setTextRise(rise);
image = Image.getInstance(pdfImagePO.getImageByte()); c = waterMarkName.charAt(k);
} else { under.showText(c + "");
return; }
} // 添加水印文字
// 将表格添加到文档 under.endText();
document.add(image); }
} stamper.close();
} catch (Exception e) {
/** LOGGER.error("【PDF】添加水印字符串失败:" + e.getMessage(), e);
* 加水印(字符串) } finally {
* try {
* @param inputFile 需要加水印的PDF路径 if (os != null) {
* @param outputFile 输出生成PDF的路径 os.close();
* @param waterMarkName 水印字符 }
*/ if (reader != null) {
public static void stringWaterMark(String filePath, String waterMarkName) { reader.close();
PdfReader reader = null; }
PdfStamper stamper = null; if (stamper != null) {
OutputStream os = null; stamper.close();
try { }
reader = new PdfReader(filePath); } catch (Exception e) {
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(); * @param inputFile
char c = 0; * 需要加水印的PDF路径
int rise = 0; * @param outputFile
// 给每一页加水印 * 输出生成PDF的路径
for (int i = 1; i < total; i++) { * @param imageFile
rise = 400; * 水印图片路径
under = stamper.getUnderContent(i); */
under.beginText(); // public static void imageWaterMark(String inputFile, String imageFile) {
under.setFontAndSize(bfChinese, 30); // try {
under.setTextMatrix(200, 120); // String[] spe = separatePath(inputFile);
for (int k = 0; k < j; k++) { // String outputFile = spe[0] + "_WM." + spe[1];
under.setTextRise(rise); //
c = waterMarkName.charAt(k); // PdfReader reader = new PdfReader(inputFile);
under.showText(c + ""); // PdfStamper stamper = new PdfStamper(reader, new
} // FileOutputStream(outputFile));
// 添加水印文字 //
under.endText(); // int total = reader.getNumberOfPages() + 1;
} //
stamper.close(); // Image image = Image.getInstance(imageFile);
} catch (Exception e) { // image.setAbsolutePosition(-100, 0);// 坐标
LOGGER.error("【PDF】添加水印字符串失败:" + e.getMessage(), e); // image.scaleAbsolute(800, 1000);// 自定义大小
} finally { // // image.setRotation(-20);//旋转 弧度
try { // // image.setRotationDegrees(-45);//旋转 角度
if (os != null) { // // image.scalePercent(50);//依照比例缩放
os.close(); // PdfGState gs = new PdfGState();
} // gs.setFillOpacity(0.2f);// 设置透明度为0.2
if (reader != null) { // PdfContentByte under;
reader.close(); // // 给每一页加水印
} // for (int i = 1; i < total; i++) {
if (stamper != null) { // under = stamper.getUnderContent(i);
stamper.close(); // under.beginText();
} // // 添加水印图片
} catch (Exception e) { // under.addImage(image);
} // under.setGState(gs);
} // }
} // stamper.close();
// } catch (Exception e) {
/** // e.printStackTrace();
* 加水印(图片) // }
* // }
* @param inputFile
* 需要加水印的PDF路径 /**
* @param outputFile * 结束关闭文件流
* 输出生成PDF的路径 *
* @param imageFile * @param document
* 水印图片路径 * @param os
*/ */
// public static void imageWaterMark(String inputFile, String imageFile) { private static void close(Document document, OutputStream os, PdfWriter pdfWriter) {
// try { try {
// String[] spe = separatePath(inputFile); if (document != null) {
// String outputFile = spe[0] + "_WM." + spe[1]; document.close();
// document = null;
// PdfReader reader = new PdfReader(inputFile); }
// PdfStamper stamper = new PdfStamper(reader, new if (os != null) {
// FileOutputStream(outputFile)); os.close();
// os = null;
// int total = reader.getNumberOfPages() + 1; }
// if (pdfWriter != null) {
// Image image = Image.getInstance(imageFile); pdfWriter.close();
// image.setAbsolutePosition(-100, 0);// 坐标 }
// image.scaleAbsolute(800, 1000);// 自定义大小 } catch (Exception e) {
// // image.setRotation(-20);//旋转 弧度 LOGGER.error("【PDF】PDF文件流关闭失败:" + e.getMessage(), e);
// // 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 @@ ...@@ -233,14 +233,6 @@
</dependency> </dependency>
<!-- Common Dependency End --> <!-- 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 --> <!-- logback-json -->
<dependency> <dependency>
<groupId>ch.qos.logback.contrib</groupId> <groupId>ch.qos.logback.contrib</groupId>
...@@ -258,18 +250,14 @@ ...@@ -258,18 +250,14 @@
<version>0.1.2</version> <version>0.1.2</version>
</dependency> </dependency>
<!-- Others Begin -->
<dependency> <!-- Mysql Driver Begin -->
<groupId>org.jboss.netty</groupId>
<artifactId>netty</artifactId>
<version>3.2.10.Final</version>
</dependency>
<dependency> <dependency>
<groupId>org.apache.activemq</groupId> <groupId>mysql</groupId>
<artifactId>activemq-all</artifactId> <artifactId>mysql-connector-java</artifactId>
<version>5.15.0</version> <version>6.0.6</version>
</dependency> </dependency>
<!-- Others End --> <!-- Mysql Driver End -->
<!-- 图片处理工具 added by songx at 2017-05-17 --> <!-- 图片处理工具 added by songx at 2017-05-17 -->
<dependency> <dependency>
...@@ -297,13 +285,6 @@ ...@@ -297,13 +285,6 @@
<version>3.0.0</version> <version>3.0.0</version>
</dependency> </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 --> <!-- 阿里云媒体转码SDK包 added by songx at 2017-06-22 -->
<dependency> <dependency>
<groupId>com.aliyun</groupId> <groupId>com.aliyun</groupId>
...@@ -320,6 +301,7 @@ ...@@ -320,6 +301,7 @@
<artifactId>aliyun-java-sdk-mts</artifactId> <artifactId>aliyun-java-sdk-mts</artifactId>
<version>2.1.7</version> <version>2.1.7</version>
</dependency> </dependency>
<!-- end -->
<!-- solr add by gaop at 2018-4-23 11:33:47 --> <!-- solr add by gaop at 2018-4-23 11:33:47 -->
<dependency> <dependency>
...@@ -327,7 +309,6 @@ ...@@ -327,7 +309,6 @@
<artifactId>spring-data-solr</artifactId> <artifactId>spring-data-solr</artifactId>
<version>${spring.data.solr.version}</version> <version>${spring.data.solr.version}</version>
</dependency> </dependency>
<!-- end -->
<!-- Jackson Begin --> <!-- Jackson Begin -->
<dependency> <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