当前位置:   article > 正文

Android使用iText7生成PDF文件_android com.itextpdf

android com.itextpdf

一:添加依赖

implementation 'com.itextpdf:itext7-core:7.1.13'

二:清单文件AndroidManifest.xml

添加权限

  1. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  2. <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
  3. <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>

在<application>中添加

android:requestLegacyExternalStorage="true"

添加provider

  1. <provider
  2. android:name="androidx.core.content.FileProvider"
  3. android:authorities="com.example.demo.fileprovider"
  4. android:exported="false"
  5. android:grantUriPermissions="true">
  6. <meta-data
  7. android:name="android.support.FILE_PROVIDER_PATHS"
  8. android:resource="@xml/provider_paths" />
  9. </provider>

在res目录下新建xml目录,并创建provider_paths.xml文件

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <paths>
  3. <external-path name="external_files" path="."/>
  4. </paths>

三:文件工具类FileUtils

  1. package com.example.demo;
  2. import android.content.ActivityNotFoundException;
  3. import android.content.Context;
  4. import android.content.Intent;
  5. import android.content.pm.PackageManager;
  6. import android.content.pm.ResolveInfo;
  7. import android.net.Uri;
  8. import android.widget.Toast;
  9. import androidx.core.content.FileProvider;
  10. import java.io.File;
  11. import java.io.IOException;
  12. import java.util.List;
  13. public class FileUtils {
  14. /**
  15. * 获取包含文件的应用程序路径
  16. *
  17. * @return String 根目录路径
  18. */
  19. public static String getAppPath() {
  20. File dir = new File(android.os.Environment.getExternalStorageDirectory()
  21. + File.separator
  22. + "PDF"
  23. + File.separator);
  24. if (!dir.exists()) {
  25. dir.mkdirs();
  26. }
  27. return dir.getPath() + File.separator;
  28. }
  29. /**
  30. * 打开PDF文件
  31. * @param context
  32. * @param url
  33. * @throws ActivityNotFoundException
  34. * @throws IOException
  35. */
  36. public static void openFile(Context context, File url) throws ActivityNotFoundException {
  37. if (url.exists()) {
  38. Uri uri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".fileprovider", url);
  39. String urlString = url.toString().toLowerCase();
  40. Intent intent = new Intent(Intent.ACTION_VIEW);
  41. intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
  42. /**
  43. * Security
  44. */
  45. List<ResolveInfo> resInfoList = context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
  46. for (ResolveInfo resolveInfo : resInfoList) {
  47. String packageName = resolveInfo.activityInfo.packageName;
  48. context.grantUriPermission(packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
  49. }
  50. // 通过比较url和扩展名,检查您要打开的文件类型。
  51. // 当if条件匹配时,插件设置正确的意图(mime)类型
  52. // 所以Android知道用什么程序打开文件
  53. if (urlString.toLowerCase().contains(".doc")
  54. || urlString.toLowerCase().contains(".docx")) {
  55. // Word document
  56. intent.setDataAndType(uri, "application/msword");
  57. } else if (urlString.toLowerCase().contains(".pdf")) {
  58. // PDF file
  59. intent.setDataAndType(uri, "application/pdf");
  60. } else if (urlString.toLowerCase().contains(".ppt")
  61. || urlString.toLowerCase().contains(".pptx")) {
  62. // Powerpoint file
  63. intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
  64. } else if (urlString.toLowerCase().contains(".xls")
  65. || urlString.toLowerCase().contains(".xlsx")) {
  66. // Excel file
  67. intent.setDataAndType(uri, "application/vnd.ms-excel");
  68. } else if (urlString.toLowerCase().contains(".zip")
  69. || urlString.toLowerCase().contains(".rar")) {
  70. // ZIP file
  71. intent.setDataAndType(uri, "application/trap");
  72. } else if (urlString.toLowerCase().contains(".rtf")) {
  73. // RTF file
  74. intent.setDataAndType(uri, "application/rtf");
  75. } else if (urlString.toLowerCase().contains(".wav")
  76. || urlString.toLowerCase().contains(".mp3")) {
  77. // WAV/MP3 audio file
  78. intent.setDataAndType(uri, "audio/*");
  79. } else if (urlString.toLowerCase().contains(".gif")) {
  80. // GIF file
  81. intent.setDataAndType(uri, "image/gif");
  82. } else if (urlString.toLowerCase().contains(".jpg")
  83. || urlString.toLowerCase().contains(".jpeg")
  84. || urlString.toLowerCase().contains(".png")) {
  85. // JPG file
  86. intent.setDataAndType(uri, "image/jpeg");
  87. } else if (urlString.toLowerCase().contains(".txt")) {
  88. // Text file
  89. intent.setDataAndType(uri, "text/plain");
  90. } else if (urlString.toLowerCase().contains(".3gp")
  91. || urlString.toLowerCase().contains(".mpg")
  92. || urlString.toLowerCase().contains(".mpeg")
  93. || urlString.toLowerCase().contains(".mpe")
  94. || urlString.toLowerCase().contains(".mp4")
  95. || urlString.toLowerCase().contains(".avi")) {
  96. // Video files
  97. intent.setDataAndType(uri, "video/*");
  98. } else {
  99. // 如果你愿意,你也可以为任何其他文件定义意图类型
  100. // 另外,使用下面的else子句来管理其他未知扩展
  101. // 在这种情况下,Android将显示设备上安装的所有应用程序
  102. // 因此您可以选择使用哪个应用程序
  103. intent.setDataAndType(uri, "*/*");
  104. }
  105. intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  106. context.startActivity(intent);
  107. } else {
  108. Toast.makeText(context, "文件不存在", Toast.LENGTH_SHORT).show();
  109. }
  110. }
  111. }

四:权限工具类Permissions

  1. package com.example.demo;
  2. import android.app.AlertDialog;
  3. import android.content.Context;
  4. import android.content.DialogInterface;
  5. import android.content.Intent;
  6. import android.net.Uri;
  7. import android.provider.Settings;
  8. public class Permissions {
  9. /**
  10. * 弹出权限提示框
  11. */
  12. public static void showPermissionsSettingDialog(Context context, String permission) {
  13. String msg = "";
  14. if (permission.equals("android.permission.READ_EXTERNAL_STORAGE") ||
  15. permission.equals("android.permission.WRITE_EXTERNAL_STORAGE")) {
  16. msg= "本App需要“允许储存空间”权限才能正常运行,请点击确定,进入设置界面进行授权处理";
  17. }
  18. AlertDialog.Builder builder = new AlertDialog.Builder(context);
  19. builder.setMessage(msg);
  20. builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
  21. @Override
  22. public void onClick(DialogInterface dialog, int which) {
  23. showSettings(context);
  24. }
  25. });
  26. builder.setCancelable(false);
  27. builder.show();
  28. }
  29. /**
  30. * 如果授权失败,就要进入App权限设置界面
  31. */
  32. public static void showSettings(Context context) {
  33. Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
  34. Uri uri = Uri.fromParts("package", context.getPackageName(), null);
  35. intent.setData(uri);
  36. intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  37. context.startActivity(intent);
  38. }
  39. }

五:布局文件activity_main.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:tools="http://schemas.android.com/tools"
  4. android:layout_width="match_parent"
  5. android:layout_height="match_parent"
  6. android:gravity="center"
  7. android:orientation="vertical"
  8. tools:context=".MainActivity">
  9. <Button
  10. android:id="@+id/create_pdf"
  11. android:layout_width="wrap_content"
  12. android:layout_height="wrap_content"
  13. android:text="生成PDF文件"
  14. android:layout_marginTop="100dp"
  15. android:layout_marginBottom="30dp"/>
  16. <Button
  17. android:id="@+id/open_pdf"
  18. android:layout_width="wrap_content"
  19. android:layout_height="wrap_content"
  20. android:text="打开PDF文件"/>
  21. </LinearLayout>

六:使用iText7生成PDF文件,并打开PDF文件

  1. package com.example.demo;
  2. import androidx.annotation.NonNull;
  3. import androidx.annotation.Nullable;
  4. import androidx.appcompat.app.AppCompatActivity;
  5. import androidx.core.app.ActivityCompat;
  6. import androidx.core.content.ContextCompat;
  7. import android.Manifest;
  8. import android.app.AlertDialog;
  9. import android.content.Context;
  10. import android.content.DialogInterface;
  11. import android.content.Intent;
  12. import android.content.pm.PackageManager;
  13. import android.os.Build;
  14. import android.os.Bundle;
  15. import android.os.Environment;
  16. import android.os.Handler;
  17. import android.provider.Settings;
  18. import android.util.Log;
  19. import android.view.View;
  20. import android.widget.Button;
  21. import android.widget.Toast;
  22. import com.itextpdf.kernel.colors.Color;
  23. import com.itextpdf.kernel.colors.DeviceRgb;
  24. import com.itextpdf.kernel.font.PdfFont;
  25. import com.itextpdf.kernel.font.PdfFontFactory;
  26. import com.itextpdf.kernel.geom.PageSize;
  27. import com.itextpdf.kernel.pdf.PdfDocument;
  28. import com.itextpdf.kernel.pdf.PdfDocumentInfo;
  29. import com.itextpdf.kernel.pdf.PdfWriter;
  30. import com.itextpdf.kernel.pdf.canvas.draw.SolidLine;
  31. import com.itextpdf.layout.Document;
  32. import com.itextpdf.layout.element.LineSeparator;
  33. import com.itextpdf.layout.element.Paragraph;
  34. import com.itextpdf.layout.element.Text;
  35. import com.itextpdf.layout.property.TextAlignment;
  36. import java.io.File;
  37. import java.io.FileNotFoundException;
  38. import java.io.FileOutputStream;
  39. import java.io.IOException;
  40. public class MainActivity extends AppCompatActivity {
  41. private Button create_pdf;
  42. private Button open_pdf;
  43. private String path;
  44. private Context context;
  45. private boolean isPermissions = false;
  46. @Override
  47. protected void onCreate(Bundle savedInstanceState) {
  48. super.onCreate(savedInstanceState);
  49. setContentView(R.layout.activity_main);
  50. requestPermission();
  51. initView();
  52. }
  53. private void initView() {
  54. create_pdf = findViewById(R.id.create_pdf);
  55. open_pdf = findViewById(R.id.open_pdf);
  56. context = getApplicationContext();
  57. path = FileUtils.getAppPath() + "test.pdf";
  58. Log.e("pdf保存路径", path);
  59. create_pdf.setOnClickListener(new View.OnClickListener() {
  60. @Override
  61. public void onClick(View v) {
  62. createPDF(path);
  63. }
  64. });
  65. open_pdf.setOnClickListener(new View.OnClickListener() {
  66. @Override
  67. public void onClick(View v) {
  68. openPDF();
  69. }
  70. });
  71. }
  72. /**
  73. * 创建PDF文件
  74. */
  75. private void createPDF(String path) {
  76. if (isPermissions) {
  77. File file = new File(path);
  78. if (file.exists()) {
  79. file.delete();
  80. }
  81. file.getParentFile().mkdirs();
  82. // 创建Document
  83. PdfWriter writer = null;
  84. try {
  85. writer = new PdfWriter(new FileOutputStream(path));
  86. } catch (FileNotFoundException e) {
  87. Log.e("FileNotFoundException", e.toString());
  88. }
  89. PdfDocument pdf_document = new PdfDocument(writer);
  90. // 生成的PDF文档信息
  91. PdfDocumentInfo info = pdf_document.getDocumentInfo();
  92. // 标题
  93. info.setTitle("First pdf file");
  94. // 作者
  95. info.setAuthor("Quinto");
  96. // 科目
  97. info.setSubject("test");
  98. // 关键词
  99. info.setKeywords("pdf");
  100. // 创建日期
  101. info.setCreator("2022-10-20");
  102. Document document = new Document(pdf_document, PageSize.A4, true);
  103. // 文字字体(显示中文)、大小、颜色
  104. PdfFont font = null;
  105. try {
  106. font = PdfFontFactory.createFont("STSong-Light","UniGB-UCS2-H");
  107. } catch (IOException e) {
  108. Log.e("IOException", e.toString());
  109. }
  110. float title_size = 36.0f;
  111. float text_title_size = 30.0f;
  112. float text_size = 24.0f;
  113. Color title_color = new DeviceRgb(0, 0, 0);
  114. Color text_title_color = new DeviceRgb(65, 136, 160);
  115. Color text_color = new DeviceRgb(43, 43, 43);
  116. // 行分隔符
  117. // 实线:SolidLine() 点线:DottedLine() 仪表盘线:DashedLine()
  118. LineSeparator separator = new LineSeparator(new SolidLine());
  119. separator.setStrokeColor(new DeviceRgb(0, 0, 68));
  120. // 添加大标题
  121. Text title = new Text("这里是pdf文件标题").setFont(font).setFontSize(title_size).setFontColor(title_color);
  122. Paragraph paragraph_title = new Paragraph(title).setTextAlignment(TextAlignment.CENTER);
  123. document.add(paragraph_title);
  124. for (int i = 1; i < 10; i++) {
  125. // 添加文本小标题
  126. Text text_title = new Text("第" + i + "行:").setFont(font).setFontSize(text_title_size).setFontColor(text_title_color);
  127. Paragraph paragraph_text_title = new Paragraph(text_title);
  128. document.add(paragraph_text_title);
  129. // 添加文本内容
  130. String content = "我是文本内容" + i + i + i + i + i + i + i + i + i + i;
  131. Text text = new Text(content).setFont(font).setFontSize(text_size).setFontColor(text_color);
  132. Paragraph paragraph_text = new Paragraph(text);
  133. document.add(paragraph_text);
  134. // 添加可换行空间
  135. document.add(new Paragraph(""));
  136. // 添加水平线
  137. document.add(separator);
  138. // 添加可换行空间
  139. document.add(new Paragraph(""));
  140. }
  141. /**
  142. * 添加列表
  143. */
  144. List list = new List().setSymbolIndent(12).setListSymbol("\u2022").setFont(font);
  145. list.add(new ListItem("列表1"))
  146. .add(new ListItem("列表2"))
  147. .add(new ListItem("列表3"));
  148. document.add(list);
  149. /**
  150. * 添加图片
  151. */
  152. Text text_image = new Text("图片:").setFont(font).setFontSize(text_title_size).setFontColor(text_title_color);
  153. Paragraph image = new Paragraph(text_image);
  154. document.add(image);
  155. Image image1 = null;
  156. Image image2 = null;
  157. Image image3 = null;
  158. try {
  159. image1 = new Image(ImageDataFactory.create("/storage/emulated/0/DCIM/Camera/IMG_20221003_181926.jpg")).setWidth(PageSize.A4.getWidth() * 2 / 3);
  160. image2 = new Image(ImageDataFactory.create("/storage/emulated/0/Download/互传/folder/证件/XHS_159716343059020494b83-da6a-39d7-ae3b-13fd92cfbb53.jpg")).setWidth(PageSize.A4.getWidth() / 3) ;
  161. image3 = new Image(ImageDataFactory.create("/storage/emulated/0/Download/互传/folder/证件/XHS_1597163520524f0b4df77-8db1-35c6-9dfa-3e0aa74f1fef.jpg")).setWidth(PageSize.A4.getWidth() / 3);
  162. } catch (MalformedURLException e) {
  163. Log.e("MalformedURLException", e.toString());
  164. }
  165. Paragraph paragraph_image = new Paragraph().add(image1)
  166. .add(" ")
  167. .add(image2)
  168. .add(" ")
  169. .add(image3);
  170. document.add(paragraph_image);
  171. document.add(new Paragraph(""));
  172. /**
  173. * 添加表格
  174. */
  175. Text text_table = new Text("表单:").setFont(font).setFontSize(text_title_size).setFontColor(text_title_color);
  176. Paragraph paragraph_table = new Paragraph(text_table);
  177. document.add(paragraph_table);
  178. // 3列
  179. float[] pointColumnWidths = {100f, 100f, 100f};
  180. Table table = new Table(pointColumnWidths);
  181. // 设置边框样式、颜色、宽度
  182. Color table_color = new DeviceRgb(80, 136, 255);
  183. Border border = new DottedBorder(table_color, 3);
  184. table.setBorder(border);
  185. // 设置单元格文本居中
  186. table.setTextAlignment(TextAlignment.CENTER);
  187. // 添加单元格内容
  188. Color table_header = new DeviceRgb(0, 0, 255);
  189. Color table_content = new DeviceRgb(255, 0, 0);
  190. Color table_footer = new DeviceRgb(0, 255, 0);
  191. Text text1 = new Text("姓名").setFont(font).setFontSize(20.0f).setFontColor(table_header);
  192. Text text2 = new Text("年龄").setFont(font).setFontSize(20.0f).setFontColor(table_header);
  193. Text text3 = new Text("性别").setFont(font).setFontSize(20.0f).setFontColor(table_header);
  194. table.addHeaderCell(new Paragraph(text1));
  195. table.addHeaderCell(new Paragraph(text2));
  196. table.addHeaderCell(new Paragraph(text3));
  197. Text text4 = new Text("张三").setFont(font).setFontSize(15.0f).setFontColor(table_content);
  198. Text text5 = new Text("30").setFont(font).setFontSize(15.0f).setFontColor(table_content);
  199. Text text6 = new Text("男").setFont(font).setFontSize(15.0f).setFontColor(table_content);
  200. table.addCell(new Paragraph(text4));
  201. table.addCell(new Paragraph(text5));
  202. table.addCell(new Paragraph(text6));
  203. Text text7 = new Text("丽萨").setFont(font).setFontSize(15.0f).setFontColor(table_footer);
  204. Text text8 = new Text("20").setFont(font).setFontSize(15.0f).setFontColor(table_footer);
  205. Text text9 = new Text("女").setFont(font).setFontSize(15.0f).setFontColor(table_footer);
  206. table.addFooterCell(new Paragraph(text7));
  207. table.addFooterCell(new Paragraph(text8));
  208. table.addFooterCell(new Paragraph(text9));
  209. // 将表格添加进pdf文件
  210. document.add(table);
  211. /**
  212. * 添加页眉、页脚、水印
  213. */
  214. Rectangle pageSize;
  215. PdfCanvas canvas;
  216. int n = pdf_document.getNumberOfPages();
  217. for (int i = 1; i <= n; i++) {
  218. PdfPage page = pdf_document.getPage(i);
  219. pageSize = page.getPageSize();
  220. canvas = new PdfCanvas(page);
  221. // 页眉
  222. canvas.beginText().setFontAndSize(font, 7)
  223. .moveText(pageSize.getWidth() / 2 - 18, pageSize.getHeight() - 10)
  224. .showText("我是页眉")
  225. .endText();
  226. // 页脚
  227. canvas.setStrokeColor(text_color)
  228. .setLineWidth(.2f)
  229. .moveTo(pageSize.getWidth() / 2 - 30, 20)
  230. .lineTo(pageSize.getWidth() / 2 + 30, 20).stroke();
  231. canvas.beginText().setFontAndSize(font, 7)
  232. .moveText(pageSize.getWidth() / 2 - 6, 10)
  233. .showText(String.valueOf(i))
  234. .endText();
  235. // 水印
  236. Paragraph p = new Paragraph("Quinto").setFontSize(60);
  237. canvas.saveState();
  238. PdfExtGState gs1 = new PdfExtGState().setFillOpacity(0.2f);
  239. canvas.setExtGState(gs1);
  240. document.showTextAligned(p, pageSize.getWidth() / 2, pageSize.getHeight() / 2,
  241. pdf_document.getPageNumber(page),
  242. TextAlignment.CENTER, VerticalAlignment.MIDDLE, 45);
  243. canvas.restoreState();
  244. }
  245. // 关闭
  246. document.close();
  247. Toast.makeText(this, "PDF文件已生成", Toast.LENGTH_SHORT).show();
  248. } else {
  249. requestPermission();
  250. }
  251. }
  252. /**
  253. * 打开PDF文件
  254. */
  255. private void openPDF() {
  256. new Handler().postDelayed(new Runnable() {
  257. @Override
  258. public void run() {
  259. try {
  260. FileUtils.openFile(context, new File(path));
  261. } catch (Exception e) {
  262. Log.e("Exception", e.toString());
  263. }
  264. }
  265. }, 1000);
  266. }
  267. /**
  268. * 动态申请权限
  269. */
  270. private void requestPermission() {
  271. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
  272. // 先判断有没有权限
  273. if (Environment.isExternalStorageManager()) {
  274. isPermissions = true;
  275. } else {
  276. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  277. builder.setMessage("生成PDF文件需要“允许所有文件访问”权限才能正常运行,请点击确定,进入设置界面进行授权处理");
  278. builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
  279. @Override
  280. public void onClick(DialogInterface dialog, int which) {
  281. startActivityForResult(new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION), 1024);
  282. }
  283. });
  284. builder.setCancelable(false);
  285. builder.show();
  286. }
  287. } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  288. // 先判断有没有权限
  289. if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED &&
  290. ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
  291. isPermissions = true;
  292. } else {
  293. ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1024);
  294. }
  295. } else {
  296. isPermissions = true;
  297. }
  298. }
  299. @Override
  300. public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
  301. super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  302. if (requestCode == 1024) {
  303. if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED &&
  304. ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
  305. isPermissions = true;
  306. } else {
  307. //拒绝就要强行跳转设置界面
  308. Permissions.showPermissionsSettingDialog(this, permissions[0]);
  309. }
  310. }
  311. }
  312. @Override
  313. protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent intent) {
  314. super.onActivityResult(requestCode, resultCode, intent);
  315. if (requestCode == 1024 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
  316. if (Environment.isExternalStorageManager()) {
  317. isPermissions = true;
  318. } else {
  319. Toast.makeText(context, "存储权限获取失败", Toast.LENGTH_SHORT).show();
  320. }
  321. }
  322. }
  323. }

七:生成的PDF文件预览图

 

 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/319170
推荐阅读
相关标签
  

闽ICP备14008679号