【java】将PDF转成字符串
生活随笔
收集整理的這篇文章主要介紹了
【java】将PDF转成字符串
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
背景
我們在日常編程中,可能會遇到,無法直接傳送PDF文件的情況,這就需要將PDF轉成字符串。待接收方收到字符串再將字符串轉成PDF文件。
代碼
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream;import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder;public class PdfToBinaryUtil {static BASE64Encoder encoder = new BASE64Encoder();static BASE64Decoder decoder = new BASE64Decoder();public static void main(String[] args) {String base64String = getPDFBinary("q.pdf");System.out.println(base64String);//FileTool.writeStringToFile(base64String, "1.txt");//FileTool可參考https://blog.csdn.net/Kangyucheng/article/details/86981414base64StringToPDF(base64String, "1.pdf");}public static String getPDFBinary(String filePath) {File file = new File(filePath);try {FileInputStream fileInputStream = new FileInputStream(file);BufferedInputStream bufferInputStream = new BufferedInputStream(fileInputStream);ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();BufferedOutputStream bout = new BufferedOutputStream(byteArrayOutputStream);byte[] buffer = new byte[1024];int len = bufferInputStream.read(buffer);while (len != -1) {bout.write(buffer, 0, len);len = bufferInputStream.read(buffer);}bout.flush();byte[] bytes = byteArrayOutputStream.toByteArray();bufferInputStream.close();return encoder.encodeBuffer(bytes).trim();} catch (Exception e) {e.printStackTrace();}return null;}public static void base64StringToPDF(String base64String, String newFile) {try {byte[] bytes = decoder.decodeBuffer(base64String);ByteArrayInputStream bais = new ByteArrayInputStream(bytes);BufferedInputStream bin = new BufferedInputStream(bais);File file = new File(newFile);FileOutputStream fout = new FileOutputStream(file);BufferedOutputStream bout = new BufferedOutputStream(fout);byte[] buffers = new byte[1024];int len = bin.read(buffers);while (len != -1) {bout.write(buffers, 0, len);len = bin.read(buffers);}bout.flush();bout.close();} catch (Exception e) {e.printStackTrace();}}}輸出:
節選最后幾行
| MDAwMDAgbg0KMDAwMDgwNDEyNSAwMDAwMCBuDQowMDAwODA0NDY1IDAwMDAwIG4NCjAwMDA4MDQ3 MzUgMDAwMDAgbg0KMDAwMDgwNDk2MyAwMDAwMCBuDQp0cmFpbGVyDQo8PC9TaXplIDQ4MC9Sb290 IDEgMCBSL0luZm8gODkgMCBSL0lEWzxGQkUzQUE2MUI2RDk2MDQwQTQwMTUwNjI0OEQ5RjY5Qj48 RkJFM0FBNjFCNkQ5NjA0MEE0MDE1MDYyNDhEOUY2OUI+XSA+Pg0Kc3RhcnR4cmVmDQo4MDYyNjAN CiUlRU9GDQp4cmVmDQowIDANCnRyYWlsZXINCjw8L1NpemUgNDgwL1Jvb3QgMSAwIFIvSW5mbyA4 OSAwIFIvSURbPEZCRTNBQTYxQjZEOTYwNDBBNDAxNTA2MjQ4RDlGNjlCPjxGQkUzQUE2MUI2RDk2 MDQwQTQwMTUwNjI0OEQ5RjY5Qj5dIC9QcmV2IDgwNjI2MC9YUmVmU3RtIDgwNDk2Mz4+DQpzdGFy dHhyZWYNCjgxNjAyMA0KJSVFT0Y= |
?
總結
以上是生活随笔為你收集整理的【java】将PDF转成字符串的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【java】简单的方式实现文本文件的读写
- 下一篇: 百练OJ:4150:上机