大家好,图片格式转换网站源码分享相信很多的网友都不是很明白,包括图片在线格式转换网站也是一样,不过没有关系,接下来就来为大家分享关于图片格式转换网站源码分享和图片在线格式转换网站的一些知识点,大家可以关注收藏,免得下次来找不到哦,下面我们开始吧!
之前在写文档在线预览时留下了一个小坑,当时比较推荐的做法是将各种类型的文档都由后端统一转成pdf格式再由前端进行展示,但是当时并没有提供将各种类型的文档转pdf的方法,这次就来填一下这个坑。前端在线预览pdf文件的实现方式可以参考这篇文章:《java接口返回图片链接或pdf链接如何设置在线预览还是下载》。
事前准备
代码基于aspose-words(用于word、txt转pdf),itextpdf(用于ppt、图片、excel转pdf),poi(用于word转pdf),spire(用于word、excel转pdf)所以事先需要在项目里下面以下依赖
1、需要的maven依赖
\t\t<!–不使用aspose-words方式可不引用–>\n\t\t<dependency>\n\t\t\t<groupId>com.luhuiguo</groupId>\n\t\t\t<artifactId>aspose-words</artifactId>\n\t\t\t<version>23.1</version>\n\t\t</dependency>\n\t\t<!–poi–>\n\t\t<dependency>\n<groupId>org.apache.poi</groupId>\n<artifactId>poi</artifactId>\n<version>5.2.0</version>\n</dependency>\n<dependency>\n<groupId>org.apache.poi</groupId>\n<artifactId>poi-ooxml</artifactId>\n<version>5.2.0</version>\n</dependency>\n<dependency>\n<groupId>org.apache.poi</groupId>\n<artifactId>poi-scratchpad</artifactId>\n<version>5.2.0</version>\n</dependency>\n<dependency>\n<groupId>org.apache.poi</groupId>\n<artifactId>poi-excelant</artifactId>\n<version>5.2.0</version>\n</dependency>\n<!–itextpdf–>\n<dependency>\n<groupId>com.itextpdf</groupId>\n<artifactId>itextpdf</artifactId>\n<version>5.5.13.2</version>\n</dependency>\n<dependency>\n<groupId>com.itextpdf</groupId>\n<artifactId>itext-asian</artifactId>\n<version>5.2.0</version>\n</dependency>\t\t
添加spire依赖(商用,有免费版,但是存在页数和字数限制,不采用spire方式可不添加)
spire在添加pom之前还得先添加maven仓库来源
\t\t<repository>\n<id>com.e-iceblue</id>\n<name>e-iceblue</name>\n<url>https://repo.e-iceblue.cn/repository/maven-public/</url>\n</repository>
接着在项目的pom文件里添加如下依赖
免费版:
\t\t<dependency>\n<groupId>e-iceblue</groupId>\n<artifactId>spire.office.free</artifactId>\n<version>5.3.1</version>\n</dependency>
付费版版:
\t\t<dependency>\n<groupId>e-iceblue</groupId>\n<artifactId>spire.office</artifactId>\n<version>5.3.1</version>\n</dependency>
2、后面用到的工具类代码:
packagecom.fhey.service.common.utils.file;\n\nimportcn.hutool.core.util.StrUtil;\nimportorg.slf4j.Logger;\nimportorg.slf4j.LoggerFactory;\nimportjava.io.File;\nimportjava.io.FileInputStream;\nimportjava.io.IOException;\n\n/**\n*@authorfhey\n*@date2023-04-2011:15:58\n*@description:文件工具类\n*/\npublicclassFileUtil{\nprivatestaticfinalLoggerlogger=LoggerFactory.getLogger(FileUtil.class);\n\n//获取新文件的全路径\npublicstaticStringgetNewFileFullPath(StringsourceFilePath,StringdestFilePath,Stringext){\nFiledestFile=newFile(destFilePath);\nif(destFile.isFile()){\nreturndestFilePath;\n}\nFilesourceFile=newFile(sourceFilePath);\nStringsourceFileName=sourceFile.getName();\nif(sourceFile.isFile()){\nreturndestFilePath+File.separator+sourceFileName.substring(0,sourceFileName.lastIndexOf(StrUtil.DOT))+StrUtil.DOT+ext;\n}\nreturndestFilePath+File.separator+sourceFileName+StrUtil.DOT+ext;\n}\n\n//判断文件是否是图片\npublicstaticbooleanisImage(Filefile)throwsIOException{\nFileInputStreamis=newFileInputStream(file);\nbyte[]bytes=newbyte[8];\nis.read(bytes);\nis.close();\nStringtype=bytesToHexString(bytes).toUpperCase();\nif(type.contains(&34;)//JPEG(jpg)\n||type.contains(&34;)//PNG\n||type.contains(&34;)//GIF\n||type.contains(&34;)//TIFF(tif)\n||type.contains(&34;)//Bitmap(bmp)\n){\nreturntrue;\n}\nreturnfalse;\n}\n\n//将文件头转换成16进制字符串\npublicstaticStringbytesToHexString(byte[]src){\nStringBuilderbuilder=newStringBuilder();\nif(src==null||src.length<=0){\nreturnnull;\n}\nfor(inti=0;i<src.length;i++){\nintv=src[i]&0xFF;\nStringhv=Integer.toHexString(v);\nif(hv.length()<2){\nbuilder.append(0);\n}\nbuilder.append(hv);\n}\nreturnbuilder.toString();\n}\n}
一、word文件转pdf文件(支持doc、docx)
1、使用aspose方式
验证代码:
word转pdf的方法比较简单,aspose-words基本都被帮我们搞定了,doc、docx都能支持。
代码:
publicstaticvoidwordToPdf(StringwordPath,StringpdfPath)throwsException{\npdfPath=FileUtil.getNewFileFullPath(wordPath,pdfPath,&34;);\nFilefile=newFile(pdfPath);\nFileOutputStreamos=newFileOutputStream(file);\nDocumentdoc=newDocument(wordPath);\ndoc.save(os,com.aspose.words.SaveFormat.PDF);\n}
验证代码:
publicstaticvoidmain(String[]args)throwsException{\nwordToPdf(&34;,&34;);\n}
转换效果如下,格式、图文都没什么问题,doc、docx经过验证也都能转换成功
2、使用poi方式
代码:
publicvoidwordToPdf(StringwordPath,StringpdfPath)throwsException{\npdfPath=FileUtil.getNewFileFullPath(wordPath,pdfPath,&34;);\ntry(FileInputStreamfileInputStream=newFileInputStream(wordPath);\nFileOutputStreamfileOutputStream=newFileOutputStream(pdfPath)){\nStringext=wordPath.substring(wordPath.lastIndexOf(&34;));\nXWPFDocumentdocument=null;\nif(&34;.equals(ext)){\ndocument=newXWPFDocument(fileInputStream);\n}elseif(&34;.equals(ext)){\nHWPFDocumenthwpfDocument=newHWPFDocument(fileInputStream);\ndocument=hwPFDocumentToXWPFDocument(hwpfDocument);//有问题\n}else{\nthrownewException(&34;);\n}\ndocument.write(newFileOutputStream(&34;));\nPdfOptionspdfOptions=PdfOptions.create();\nPdfConverter.getInstance().convert(document,fileOutputStream,pdfOptions);\ndocument.close();\n}\n}\n\npublicXWPFDocumenthwPFDocumentToXWPFDocument(HWPFDocumenthwpfDocument)throwsException{\nXWPFDocumentxwpfDocument=newXWPFDocument();\nxwpfDocument.createStyles();\nRangerange=hwpfDocument.getRange();\nfor(inti=0;i<range.numParagraphs();i++){\nParagraphparagraph=range.getParagraph(i);\nXWPFParagraphxwpfParagraph=xwpfDocument.createParagraph();\nif(paragraph.isInTable()){\nTabletable=range.getTable(paragraph);\nif(table!=null&&table.numRows()>0){\nintrows=table.numRows();\nintcols=table.getRow(0).numCells();\nXWPFTablexwpfTable=xwpfDocument.createTable(rows,cols);\nfor(intr=0;r<rows;r++){\nTableRowtableRow=table.getRow(r);\nif(tableRow!=null&&tableRow.numCells()>0){\nfor(intc=0;c<cols;c++){\nTableCelltableCell=tableRow.getCell(c);\nif(tableCell!=null){\nXWPFTableCellxwpfTableCell=xwpfTable.getRow(r).getCell(c);\nxwpfTableCell.setText(tableCell.text());\n}\n}\n}\n}\n}\n}else{\nList<Picture>allPictures=hwpfDocument.getPicturesTable().getAllPictures();\nintd=0;\nfor(intj=0;j<paragraph.numCharacterRuns();j++){\nCharacterRunrun=paragraph.getCharacterRun(j);\nPicturepicture=hwpfDocument.getPicturesTable().extractPicture(run,false);\nif(picture!=null){\nbyte[]pictureBytes=picture.getContent();\nStringpictureType=picture.getMimeType();\nStringfileName=picture.suggestFullFileName();\nintpictureType1=getPictureType(pictureType);\nif(pictureType1==0){\ncontinue;\n}\nif(d>0){\ncontinue;\n}\nInputStreaminputStream=newByteArrayInputStream(pictureBytes);\nXWPFParagraphpictureParagraph=xwpfDocument.createParagraph();\nXWPFRunpictureRun=pictureParagraph.createRun();\npictureRun.addPicture(inputStream,pictureType1,fileName,Units.toEMU(picture.getWidth()),Units.toEMU(picture.getHeight()));\n\n//重新设置字体和格式设置\nintsize=xwpfParagraph.getRuns().size();\nif(size==0){\ncontinue;\n}\nXWPFRunpreviousRun=xwpfParagraph.getRuns().get(size-1);\npictureRun.setFontFamily(previousRun.getFontFamily());\npictureRun.setFontSize(previousRun.getFontSize());\npictureRun.setBold(previousRun.isBold());\npictureRun.setItalic(previousRun.isItalic());\n//可根据需要设置其他格式设置\nxwpfParagraph.addRun(pictureRun);\nd++;\n}else{\nXWPFRunxwpfRun=xwpfParagraph.createRun();\nxwpfRun.setText(run.text());\n}\n}\n}\n}\nhwpfDocument.close();\nreturnxwpfDocument;\n}\n\npublicstaticintgetPictureType(StringmimeType){\nif(mimeType.equals(&34;)){\nreturnDocument.PICTURE_TYPE_JPEG;\n}elseif(mimeType.equals(&34;)){\nreturnDocument.PICTURE_TYPE_PNG;\n}elseif(mimeType.equals(&34;)){\nreturnDocument.PICTURE_TYPE_GIF;\n}elseif(mimeType.equals(&34;)){\nreturnDocument.PICTURE_TYPE_BMP;\n}else{\nreturn0;\n//thrownewRuntimeException(&34;+mimeType+&34;);\n}\n}
验证代码:
3、使用spire方式
代码:
publicvoidwordToPdf(StringwordPath,StringpdfPath)throwsException{\npdfPath=FileUtil.getNewFileFullPath(wordPath,pdfPath,&34;);\ntry(FileInputStreamfileInputStream=newFileInputStream(wordPath);\nFileOutputStreamfileOutputStream=newFileOutputStream(pdfPath)){\nStringext=wordPath.substring(wordPath.lastIndexOf(&34;));\nXWPFDocumentdocument=null;\nif(&34;.equals(ext)){\ndocument=newXWPFDocument(fileInputStream);\n}elseif(&34;.equals(ext)){\nHWPFDocumenthwpfDocument=newHWPFDocument(fileInputStream);\ndocument=hwPFDocumentToXWPFDocument(hwpfDocument);\n}else{\nthrownewException(&34;);\n}\ndocument.write(newFileOutputStream(&34;));\nPdfOptionspdfOptions=PdfOptions.create();\nPdfConverter.getInstance().convert(document,fileOutputStream,pdfOptions);\ndocument.close();\n}\n}\n\npublicXWPFDocumenthwPFDocumentToXWPFDocument(HWPFDocumenthwpfDocument)throwsException{\nXWPFDocumentxwpfDocument=newXWPFDocument();\nxwpfDocument.createStyles();\nRangerange=hwpfDocument.getRange();\nfor(inti=0;i<range.numParagraphs();i++){\nParagraphparagraph=range.getParagraph(i);\nXWPFParagraphxwpfParagraph=xwpfDocument.createParagraph();\nif(paragraph.isInTable()){\nTabletable=range.getTable(paragraph);\nif(table!=null&&table.numRows()>0){\nintrows=table.numRows();\nintcols=table.getRow(0).numCells();\nXWPFTablexwpfTable=xwpfDocument.createTable(rows,cols);\nfor(intr=0;r<rows;r++){\nTableRowtableRow=table.getRow(r);\nif(tableRow!=null&&tableRow.numCells()>0){\nfor(intc=0;c<cols;c++){\nTableCelltableCell=tableRow.getCell(c);\nif(tableCell!=null){\nXWPFTableCellxwpfTableCell=xwpfTable.getRow(r).getCell(c);\nxwpfTableCell.setText(tableCell.text());\n}\n}\n}\n}\n}\n}else{\nList<Picture>allPictures=hwpfDocument.getPicturesTable().getAllPictures();\nintd=0;\nfor(intj=0;j<paragraph.numCharacterRuns();j++){\nCharacterRunrun=paragraph.getCharacterRun(j);\nPicturepicture=hwpfDocument.getPicturesTable().extractPicture(run,false);\nif(picture!=null){\nbyte[]pictureBytes=picture.getContent();\nStringpictureType=picture.getMimeType();\nStringfileName=picture.suggestFullFileName();\nintpictureType1=getPictureType(pictureType);\nif(pictureType1==0){\ncontinue;\n}\nif(d>0){\ncontinue;\n}\nInputStreaminputStream=newByteArrayInputStream(pictureBytes);\nXWPFParagraphpictureParagraph=xwpfDocument.createParagraph();\nXWPFRunpictureRun=pictureParagraph.createRun();\npictureRun.addPicture(inputStream,pictureType1,fileName,Units.toEMU(picture.getWidth()),Units.toEMU(picture.getHeight()));\n\n//重新设置字体和格式设置\nintsize=xwpfParagraph.getRuns().size();\nif(size==0){\ncontinue;\n}\nXWPFRunpreviousRun=xwpfParagraph.getRuns().get(size-1);\npictureRun.setFontFamily(previousRun.getFontFamily());\npictureRun.setFontSize(previousRun.getFontSize());\npictureRun.setBold(previousRun.isBold());\npictureRun.setItalic(previousRun.isItalic());\n//可根据需要设置其他格式设置\nxwpfParagraph.addRun(pictureRun);\nd++;\n}else{\nXWPFRunxwpfRun=xwpfParagraph.createRun();\nxwpfRun.setText(run.text());\n}\n}\n}\n}\nhwpfDocument.close();\nreturnxwpfDocument;\n}\n\npublicstaticintgetPictureType(StringmimeType){\nif(mimeType.equals(&34;)){\nreturnDocument.PICTURE_TYPE_JPEG;\n}elseif(mimeType.equals(&34;)){\nreturnDocument.PICTURE_TYPE_PNG;\n}elseif(mimeType.equals(&34;)){\nreturnDocument.PICTURE_TYPE_GIF;\n}elseif(mimeType.equals(&34;)){\nreturnDocument.PICTURE_TYPE_BMP;\n}else{\nreturn0;\n//thrownewRuntimeException(&34;+mimeType+&34;);\n}\n}
验证代码:
因为使用的是免费版,所以只能生成前三页。。。有超过三页需求的可以选择付费版本。
二、txt文件转pdf文件
txt文件转pdf文件代码直接复用word的即可
代码:
publicstaticvoidtxtToPdf(StringtxtPath,StringpdfPath)throwsException{\nwordToPdf(txtPath,pdfPath);\n}
验证代码:
publicstaticvoidmain(String[]args)throwsException{\ntxtToPdf(&34;,&34;);\n}
转换效果如下
三、PPT文件转pdf文件(支持ppt、pptx)
PPT文件转pdf文件,听说你们公司不让用ppt,那就让我们把ppt转成pdf再用吧。其实从这里开始代码就开始复杂起来了,这里用到了Apachepoi、itextpdf、Graphics2D三个库,于是我结合这三个库同时兼容ppt、pptx写出了第一版代码
ppt转pdf第一版代码
publicstaticvoidpptToPdf(StringpptPath,StringpdfPath)throwsIOException{\npdfPath=FileUtil.getNewFileFullPath(pptPath,pdfPath,&34;);\ncom.itextpdf.text.Documentdocument=null;\nFileOutputStreamfileOutputStream=null;\nPdfWriterpdfWriter=null;\ntry{\nInputStreaminputStream=Files.newInputStream(Paths.get(pptPath));\nSlideShow<?,?>slideShow;\nStringext=pptPath.substring(pptPath.lastIndexOf(&34;));\nif(ext.equals(&34;)){\nslideShow=newXMLSlideShow(inputStream);\n}else{\nslideShow=newHSLFSlideShow(inputStream);\n}\nDimensiondimension=slideShow.getPageSize();\nfileOutputStream=newFileOutputStream(pdfPath);\n//document=newcom.itextpdf.text.Document(newcom.itextpdf.text.Rectangle((float)dimension.getWidth(),(float)dimension.getHeight()));\ndocument=newcom.itextpdf.text.Document();\npdfWriter=PdfWriter.getInstance(document,fileOutputStream);\ndocument.open();\nfor(Slide<?,?>slide:slideShow.getSlides()){\n//设置字体,解决中文乱码\nsetPPTFont(slide,&34;);\nBufferedImagebufferedImage=newBufferedImage((int)dimension.getWidth(),(int)dimension.getHeight(),BufferedImage.TYPE_INT_RGB);\nGraphics2Dgraphics2d=bufferedImage.createGraphics();\ngraphics2d.setPaint(Color.white);\ngraphics2d.setFont(newjava.awt.Font(&34;,java.awt.Font.PLAIN,12));\nslide.draw(graphics2d);\ngraphics2d.dispose();\ncom.itextpdf.text.Imageimage=com.itextpdf.text.Image.getInstance(bufferedImage,null);\nimage.scaleToFit((float)dimension.getWidth(),(float)dimension.getHeight());\ndocument.add(image);\ndocument.newPage();\n}\n}catch(Exceptione){\ne.printStackTrace();\n}finally{\ntry{\nif(document!=null){\ndocument.close();\n}\nif(fileOutputStream!=null){\nfileOutputStream.close();\n}\nif(pdfWriter!=null){\npdfWriter.close();\n}\n}catch(IOExceptione){\ne.printStackTrace();\n}\n}\n}\n\nprivatestaticvoidsetPPTFont(Slide<?,?>slide,StringfontFamily){\n//设置字体,解决中文乱码\nfor(Shape<?,?>shape:slide.getShapes()){\nif(shapeinstanceofTextShape){\nTextShapetextShape=(TextShape)shape;\nList<TextParagraph>textParagraphs=textShape.getTextParagraphs();\nfor(TextParagraphtextParagraph:textParagraphs){\nList<TextRun>textRuns=textParagraph.getTextRuns();\nfor(TextRuntextRun:textRuns){\ntextRun.setFontFamily(fontFamily);\n}\n}\n}\n}\n}
验证代码:
publicstaticvoidmain(String[]args)throwsException{\npptToPdf(&34;,&34;);\n}
转换效果如下
可以看到转换效果并不怎么好,ppt的内容展示不全。于是我开始在网上找解决方案,结果找到了一个很神奇的解决方案,就绘制的图片先写在一个PdfPTable对象上,再把PdfPTable对象放到document离去,于是我根据这个改了改代码写出了第二版代码
ppt转pdf第二版代码
publicstaticvoidpptToPdf(StringpptPath,StringpdfPath)throwsIOException{\npdfPath=FileUtil.getNewFileFullPath(pptPath,pdfPath,&34;);\ncom.itextpdf.text.Documentdocument=null;\nFileOutputStreamfileOutputStream=null;\nPdfWriterpdfWriter=null;\ntry{\nInputStreaminputStream=Files.newInputStream(Paths.get(pptPath));\nSlideShow<?,?>slideShow;\nStringext=pptPath.substring(pptPath.lastIndexOf(&34;));\nif(ext.equals(&34;)){\nslideShow=newXMLSlideShow(inputStream);\n}else{\nslideShow=newHSLFSlideShow(inputStream);\n}\nDimensiondimension=slideShow.getPageSize();\nfileOutputStream=newFileOutputStream(pdfPath);\n//document=newcom.itextpdf.text.Document(newcom.itextpdf.text.Rectangle((float)dimension.getWidth(),(float)dimension.getHeight()));\ndocument=newcom.itextpdf.text.Document();\npdfWriter=PdfWriter.getInstance(document,fileOutputStream);\ndocument.open();\nPdfPTablepdfPTable=newPdfPTable(1);\nfor(Slide<?,?>slide:slideShow.getSlides()){\n//设置字体,解决中文乱码\nsetPPTFont(slide,&34;);\nBufferedImagebufferedImage=newBufferedImage((int)dimension.getWidth(),(int)dimension.getHeight(),BufferedImage.TYPE_INT_RGB);\nGraphics2Dgraphics2d=bufferedImage.createGraphics();\ngraphics2d.setPaint(Color.white);\ngraphics2d.setFont(newjava.awt.Font(&34;,java.awt.Font.PLAIN,12));\nslide.draw(graphics2d);\ngraphics2d.dispose();\ncom.itextpdf.text.Imageimage=com.itextpdf.text.Image.getInstance(bufferedImage,null);\nimage.scaleToFit((float)dimension.getWidth(),(float)dimension.getHeight());\n//写入单元格\npdfPTable.addCell(newPdfPCell(image,true));\ndocument.add(pdfPTable);\npdfPTable.deleteBodyRows();\ndocument.newPage();\n}\n}catch(Exceptione){\ne.printStackTrace();\n}finally{\ntry{\nif(document!=null){\ndocument.close();\n}\nif(fileOutputStream!=null){\nfileOutputStream.close();\n}\nif(pdfWriter!=null){\npdfWriter.close();\n}\n}catch(IOExceptione){\ne.printStackTrace();\n}\n}\n}
转换效果如下
可以看到ppt内容已经展示完整了,到此其实ppt转pdf功能已经基本实现了,但是显示效果依然不算完美毕竟我们其实想要的是在pdf里和在ppt看的是一样的效果,而且每页ppt的长宽其实都是一样的,所以我就在想能不能设置pdf每页的长宽,把pdf每页的长宽设置成和ppt的长宽一样。于是我开始看初始化pdfdocument的源码配置
com.itextpdf.text.Documentdocument=newcom.itextpdf.text.Document();
然后发现com.itextpdf.text.Document除了默认的构造函数外还有这这样一个构造函数:
publicDocument(RectanglepageSize){\nthis(pageSize,36.0F,36.0F,36.0F,36.0F);\n}
然后com.itextpdf.text.Rectangle类点进去就发现了可以设置长宽的构造函数:
publicRectangle(floaturx,floatury){\nthis(0.0F,0.0F,urx,ury);\n}
于是我代码中的初始化Document进行如下调整(根据第一版代码改,第二版的PdfPTable可以不用了)
document=newcom.itextpdf.text.Document();\n//改成如下\ndocument=newcom.itextpdf.text.Document(newcom.itextpdf.text.Rectangle((float)dimension.getWidth(),(float)dimension.getHeight()));
ppt转pdf第三版代码(最终版)
\tpublicvoidpptToPdf(StringpptPath,StringpdfPath)throwsIOException,DocumentException{\nList<BufferedImage>images=pptToBufferedImages(pptPath);\nif(CollectionUtils.isEmpty(images)){\nreturn;\n}\npdfPath=FileUtil.getNewFileFullPath(pptPath,pdfPath,&34;);\ntry(FileOutputStreamfileOutputStream=newFileOutputStream(pdfPath)){\nBufferedImagefirstImage=images.get(0);\ncom.itextpdf.text.Rectanglerectangle=newcom.itextpdf.text.Rectangle((float)firstImage.getWidth(),(float)firstImage.getHeight());\ncom.itextpdf.text.Documentdocument=newcom.itextpdf.text.Document(rectangle,0,0,0,0);\nPdfWriterpdfWriter=PdfWriter.getInstance(document,fileOutputStream);\ndocument.open();\nfor(BufferedImagebufferedImage:images){\ncom.itextpdf.text.Imageimage=com.itextpdf.text.Image.getInstance(bufferedImage,null);\n//image.scaleToFit((float)image.getWidth(),(float)image.getHeight());\ndocument.add(image);\ndocument.newPage();\n}\ndocument.close();\npdfWriter.close();\n}\n}\n\n\tprivatestaticList<BufferedImage>pptToBufferedImages(StringpptPath){\nList<BufferedImage>images=newArrayList<>();\ntry(SlideShow<?,?>slideShow=SlideShowFactory.create(newFile(pptPath));){\nDimensiondimension=slideShow.getPageSize();\nfor(Slide<?,?>slide:slideShow.getSlides()){\n//设置字体,解决中文乱码\nsetPPTFont(slide,&34;);\nBufferedImagebufferedImage=newBufferedImage((int)dimension.getWidth(),(int)dimension.getHeight(),BufferedImage.TYPE_INT_RGB);\nGraphics2Dgraphics2d=bufferedImage.createGraphics();\ngraphics2d.setPaint(Color.white);\ngraphics2d.setFont(newjava.awt.Font(&34;,java.awt.Font.PLAIN,12));\nslide.draw(graphics2d);\ngraphics2d.dispose();\nimages.add(bufferedImage);\n}\nreturnimages;\n}catch(Exceptione){\ne.printStackTrace();\n}\nreturnnull;\n}\n\n//设置ppt字体\nprivatestaticvoidsetPPTFont(Slide<?,?>slide,StringfontFamily){\n//设置字体,解决中文乱码\nfor(Shape<?,?>shape:slide.getShapes()){\nif(shapeinstanceofTextShape){\nTextShapetextShape=(TextShape)shape;\nList<TextParagraph>textParagraphs=textShape.getTextParagraphs();\nfor(TextParagraphtextParagraph:textParagraphs){\nList<TextRun>textRuns=textParagraph.getTextRuns();\nfor(TextRuntextRun:textRuns){\ntextRun.setFontFamily(fontFamily);\n}\n}\n}\n}\n}
转换效果如下
现在展示的效果已经和ppt上一样了,而且经过验证ppt和pptx都是可以转换成功的。
四、图片转pdf文件
图片转pdf用到了用到了Apachepoi、itextpdf两个库,因为itextpdf支持解析的图片有限,点开c读取图片的方法com.itextpdf.text.Image.getInstance,我们可以看到这样一段源码:
Imageimg;\nif(c1==71&&c2==73&&c3==70){\nGifImagegif=newGifImage(url);\nimg=gif.getImage(1);\nimg=img;\nreturnimg;\n}\n\nif(c1==255&&c2==216){\nJpegvar39=newJpeg(url);\nreturnvar39;\n}\n\nJpeg2000var38;\nif(c1==0&&c2==0&&c3==0&&c4==12){\nvar38=newJpeg2000(url);\nreturnvar38;\n}\n\nif(c1==255&&c2==79&&c3==255&&c4==81){\nvar38=newJpeg2000(url);\nreturnvar38;\n}\n\nif(c1==PngImage.PNGID[0]&&c2==PngImage.PNGID[1]&&c3==PngImage.PNGID[2]&&c4==PngImage.PNGID[3]){\nvar12=PngImage.getImage(url);\nreturnvar12;\n}\n\nif(c1==215&&c2==205){\nImgWMFvar37=newImgWMF(url);\nreturnvar37;\n}\n\nif(c1!=66||c2!=77){\nRandomAccessFileOrArrayra;\nStringfile;\nif(c1==77&&c2==77&&c3==0&&c4==42||c1==73&&c2==73&&c3==42&&c4==0){\nra=null;\n\ntry{\nif(url.getProtocol().equals(&34;)){\nfile=url.getFile();\nfile=Utilities.unEscapeURL(file);\nra=newRandomAccessFileOrArray(randomAccessSourceFactory.createBestSource(file));\n}else{\nra=newRandomAccessFileOrArray(randomAccessSourceFactory.createSource(url));\n}\n\nimg=TiffImage.getTiffImage(ra,1);\nimg.url=url;\nimg=img;\nreturnimg;\n}catch(RuntimeExceptionvar32){\nif(recoverFromImageError){\nimg=TiffImage.getTiffImage(ra,recoverFromImageError,1);\nimg.url=url;\nImagevar15=img;\nreturnvar15;\n}\n\nthrowvar32;\n}finally{\nif(ra!=null){\nra.close();\n}\n\n}\n}\n\nif(c1==151&&c2==74&&c3==66&&c4==50&&c5==13&&c6==10&&c7==26&&c8==10){\nra=null;\n\ntry{\nif(url.getProtocol().equals(&34;)){\nfile=url.getFile();\nfile=Utilities.unEscapeURL(file);\nra=newRandomAccessFileOrArray(randomAccessSourceFactory.createBestSource(file));\n}else{\nra=newRandomAccessFileOrArray(randomAccessSourceFactory.createSource(url));\n}\n\nimg=JBIG2Image.getJbig2Image(ra,1);\nimg.url=url;\nimg=img;\nreturnimg;\n}finally{\nif(ra!=null){\nra.close();\n}\n\n}\n}
由此可以可知itextpdf支持解析的图片只有gif、jpeg、png、bmp、wmf、tiff、jbig2这几种,这些其实已经基本包含了所有主流的图片格式(百度图片:所以我用的webp格式是非主流格式?),而且图片格式不是光改后缀就行的,必须要用格式转换器转换。比如下面这张图虽然后缀是jpeg,但通过查看图片信息可知实际格式是webg格式itextpdf一样无法解析
话不多说我们先结合Apachepoi、itextpdf两个库简单协议版基本的图片转换pdf代码
单图片转pdf第一版代码
publicstaticvoidimageToPdf(StringimgPath,StringpdfPath)throwsException{\npdfPath=FileUtil.getNewFileFullPath(imgPath,pdfPath,&34;);\ncom.itextpdf.text.Documentdocument=newcom.itextpdf.text.Document();\nPdfWriter.getInstance(document,Files.newOutputStream(Paths.get(pdfPath)));\ndocument.open();\ncom.itextpdf.text.Imageimage=com.itextpdf.text.Image.getInstance(imgPath);\nimage.setAlignment(com.itextpdf.text.Image.ALIGN_CENTER);\ndocument.add(image);\ndocument.close();\n}\n
验证代码:
publicstaticvoidmain(String[]args)throwsException{\nimageToPdf(&34;,&34;);\n}\n
转换效果如下
从效果可以我们可以看到这个图片其实是没有显示完全的,其实小一点的图片是没什么问题的,但是因为pdf设置的每页都是A4大小,所以在图片过大时会显示不完整,所以我们在图片过大时需要对图片进行一些调整,调整后的代码如下:
单图片转pdf第二版代码
publicstaticvoidimageToPdf(StringimgPath,StringpdfPath)throwsException{\npdfPath=FileUtil.getNewFileFullPath(imgPath,pdfPath,&34;);\ncom.itextpdf.text.Documentdocument=newcom.itextpdf.text.Document();\nPdfWriter.getInstance(document,Files.newOutputStream(Paths.get(pdfPath)));\ndocument.open();\ncom.itextpdf.text.Imageimage=com.itextpdf.text.Image.getInstance(imgPath);\nfloatwidth=image.getWidth();\nfloatheight=image.getHeight();\nfloatspace=50f;\nif(width>PageSize.A4.getWidth()-space||height>PageSize.A4.getHeight()-space){\nimage.scaleToFit(PageSize.A4.getWidth()-space,PageSize.A4.getHeight()-space);\n}\nimage.setAlignment(com.itextpdf.text.Image.ALIGN_CENTER);\ndocument.add(image);\ndocument.close();\n}
转换效果如下
可以看到现在图片已经完整的显示在pdf的页面中了,到这里你可能会有一个疑惑,为什么这次不想上面ppt转换pdf一样把pdf的页面长宽设置成和图片一样,而且去调整图片的大小呢。之所以这样做的原因是因为在接下来的多图片转换成一个pdf文件时,往往是不能确保每张图片的长宽比例是一样的,为了确保每张图片都能完整的显示,所以只能调整图片的大小。
将文件夹下的所有图片导成一个pdf
将图片一张一张的导成pdf毕竟很麻烦,比如我一个文件夹下面有很多张图片,我想将该文件夹下的所有图片都导入pdf中做个《美人谱》,我该怎么做呢?安排!于是代码调整成了下面这样
支持多图片转pdf代码:
publicstaticvoidimageToPdf(StringimagePath,StringpdfPath)throwsException{\npdfPath=FileUtil.getNewFileFullPath(imagePath,pdfPath,&34;);\nFileimageFile=newFile(imagePath);\nFile[]files;\nif(imageFile.isDirectory()){\nfiles=imageFile.listFiles();\n}else{\nfiles=newFile[]{imageFile};\n}\nimageToPdf(files,pdfPath);\n}\n\npublicstaticvoidimageToPdf(File[]imageFiles,StringpdfPath)throwsException{\ncom.itextpdf.text.Documentdocument=newcom.itextpdf.text.Document();\nPdfWriter.getInstance(document,Files.newOutputStream(Paths.get(pdfPath)));\ndocument.open();\nfor(Filefile:imageFiles){\nif(file.isFile()&&FileUtil.isImage(file)){\ntry{\ncom.itextpdf.text.Imageimage=com.itextpdf.text.Image.getInstance(file.getAbsolutePath());\nfloatwidth=image.getWidth();\nfloatheight=image.getHeight();\nfloatspace=10f;\nif(width>PageSize.A4.getWidth()-space||height>PageSize.A4.getHeight()-space){\nimage.scaleToFit(PageSize.A4.getWidth()-space,PageSize.A4.getHeight()-space);\n}\nimage.setAlignment(com.itextpdf.text.Image.ALIGN_CENTER);\n//document.setMargins(50,150,50,50);\n//document.setPageSize(newcom.itextpdf.text.Rectangle(width,height));\ndocument.newPage();\ndocument.add(image);\n}catch(Exceptione){\nlogger.error(&34;,e);\n}\n}\n}\ndocument.close();\n}
验证代码:
publicstaticvoidmain(String[]args)throwsException{\nimageToPdf(&34;,&34;);\n}
转换效果如下
五、excel文件转pdf文件
其实excel转pdf在实际的应用场景中应该比较罕见,但是前面也说了这么多文件转pdf的方式了,那excel转pdf也就一并说说吧。
1、使用itextpdf方式
代码如下:
publicstaticvoidexcelToPdf(StringexcelPath,StringpdfPath)throwsDocumentException,IOException{\npdfPath=FileUtil.getNewFileFullPath(excelPath,pdfPath,&34;);\ntry(Workbookworkbook=WorkbookFactory.create(newFile(excelPath))){\ncom.itextpdf.text.Documentdocument=newcom.itextpdf.text.Document();\nPdfWriter.getInstance(document,newFileOutputStream(pdfPath));\ndocument.open();\nBaseFontchineseFont=BaseFont.createFont(&34;,&34;,BaseFont.NOT_EMBEDDED);\nFontfont=newFont(chineseFont,12,Font.NORMAL);\nDecimalFormatdf=newDecimalFormat(&&34;C:\\\\Users\\\\jie\\\\Desktop\\\\新建MicrosoftExcel工作表.xlsx&34;D:\\\\test&34;pdf&34;C:\\\\Users\\\\jie\\\\Desktop\\\\新建MicrosoftExcel工作表.xlsx&34;D:\\\\test&34;输出文件夹&34;PDF文件所在位置&34;java.io.tmpdir&34;office2pdf-&34;soffice–invisible–convert-topdf–outdir\\&34;+tempFolder.getAbsolutePath()+&34;\\&34;+officeFile.getAbsolutePath()+&34;&34;执行office文件转换任务,命令为&34;.&34;.pdf”);\nif(!file.exists()){\n//转换失败逻辑\n}\nreturnfile;\n}
OK,关于图片格式转换网站源码分享和图片在线格式转换网站的内容到此结束了,希望对大家有所帮助。