CPDFAnnotationsExample.tsx 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. /**
  2. * Copyright © 2014-2024 PDF Technologies, Inc. All Rights Reserved.
  3. *
  4. * THIS SOURCE CODE AND ANY ACCOMPANYING DOCUMENTATION ARE PROTECTED BY INTERNATIONAL COPYRIGHT LAW
  5. * AND MAY NOT BE RESOLD OR REDISTRIBUTED. USAGE IS BOUND TO THE ComPDFKit LICENSE AGREEMENT.
  6. * UNAUTHORIZED REPRODUCTION OR DISTRIBUTION IS SUBJECT TO CIVIL AND CRIMINAL PENALTIES.
  7. * This notice may not be removed from this file.
  8. */
  9. import React, { useState, useEffect, useRef } from 'react';
  10. import { Image, Platform, StyleSheet, Text, View } from 'react-native';
  11. import { CPDFReaderView, ComPDFKit, CPDFToolbarAction, CPDFThemes } from '@compdfkit_pdf_sdk/react_native';
  12. import { useNavigation, useRoute, RouteProp } from '@react-navigation/native';
  13. import { HeaderBackButton } from '@react-navigation/elements';
  14. import { MenuProvider, Menu, MenuTrigger, MenuOptions, MenuOption } from 'react-native-popup-menu';
  15. import { SafeAreaView } from 'react-native-safe-area-context';
  16. import DocumentPicker from 'react-native-document-picker';
  17. type RootStackParamList = {
  18. CPDFReaderViewExample: { document?: string };
  19. };
  20. type CPDFReaderViewExampleScreenRouteProp = RouteProp<
  21. RootStackParamList,
  22. 'CPDFReaderViewExample'
  23. >;
  24. const CPDFAnnotationsExampleScreen = () => {
  25. const pdfReaderRef = useRef<CPDFReaderView>(null);
  26. const navigation = useNavigation();
  27. const route = useRoute<CPDFReaderViewExampleScreenRouteProp>();
  28. const [samplePDF] = useState(
  29. route.params?.document || (Platform.OS === 'android'
  30. ? 'file:///android_asset/PDF_Document.pdf'
  31. : 'PDF_Document.pdf')
  32. );
  33. const handleSave = async () => {
  34. if (pdfReaderRef.current) {
  35. const success = await pdfReaderRef.current.save();
  36. if (success) {
  37. console.log('ComPDFKitRN save() : Document saved successfully');
  38. } else {
  39. console.log('ComPDFKitRN save() : Failed to save document');
  40. }
  41. }
  42. };
  43. const menuOptions = [
  44. 'Save',
  45. 'Remove All Annotations',
  46. 'Import Annotations 1',
  47. 'Import Annotations 2',
  48. 'Export Annotations'];
  49. const handleMenuItemPress = async (action: string) => {
  50. switch (action) {
  51. case 'Save':
  52. handleSave();
  53. break;
  54. case 'Remove All Annotations':
  55. const removeResult = await pdfReaderRef.current?._pdfDocument.removeAllAnnotations();
  56. console.log('ComPDFKitRN removeAllAnnotations:', removeResult);
  57. break;
  58. case 'Import Annotations 1':
  59. try {
  60. // Select an xfdf file from the public directory and import it into the current document
  61. const pickerResult = DocumentPicker.pick({
  62. type: [DocumentPicker.types.allFiles],
  63. copyTo: 'cachesDirectory'
  64. });
  65. pickerResult.then(async (res) => {
  66. const file = res[0];
  67. console.log('fileUri:', file?.uri);
  68. console.log('fileCopyUri:', file?.fileCopyUri);
  69. console.log('fileType:', file?.type);
  70. const path = file!!.fileCopyUri!!
  71. if (!path?.endsWith('xml') && !path?.endsWith('xfdf')) {
  72. console.log('ComPDFKitRN please select xfdf format file');
  73. return;
  74. }
  75. const importResult = await pdfReaderRef.current?._pdfDocument.importAnnotations(path);
  76. console.log('ComPDFKitRN importAnnotations:', importResult);
  77. })
  78. } catch (err) {
  79. }
  80. break;
  81. case 'Import Annotations 2':
  82. // Android
  83. // import xfdf file from android assets directory
  84. const testXfdf = Platform.OS === 'android'
  85. ? 'file:///android_asset/test.xfdf'
  86. : 'test.xfdf'
  87. // import xfdf file from file path
  88. // const testXfdf = '/data/user/0/com.compdfkit.reactnative.example/xxx/xxx.xfdf';
  89. const importResult = await pdfReaderRef.current?._pdfDocument.importAnnotations(testXfdf);
  90. console.log('ComPDFKitRN importAnnotations:', importResult);
  91. break;
  92. case 'Export Annotations':
  93. const exportXfdfFilePath = await pdfReaderRef.current?._pdfDocument.exportAnnotations();
  94. console.log('ComPDFKitRN exportAnnotations:', exportXfdfFilePath);
  95. break;
  96. default:
  97. break;
  98. }
  99. };
  100. const handleBack = () => {
  101. navigation.goBack();
  102. };
  103. const renderToolbar = () => {
  104. return (
  105. <View style={styles.toolbar}>
  106. <HeaderBackButton onPress={handleBack} />
  107. <Text style={styles.toolbarTitle}>Annotations Example</Text>
  108. <Menu>
  109. <MenuTrigger>
  110. <Image source={require('../assets/more.png')} style={{ width: 24, height: 24, marginEnd: 8 }} />
  111. </MenuTrigger>
  112. <MenuOptions>
  113. {menuOptions.map((option, index) => (
  114. <MenuOption key={index} onSelect={() => handleMenuItemPress(option)}>
  115. <Text style={styles.menuOption}>{option}</Text>
  116. </MenuOption>
  117. ))}
  118. </MenuOptions>
  119. </Menu>
  120. </View>
  121. );
  122. };
  123. return (
  124. <MenuProvider>
  125. <SafeAreaView style={{ flex: 1 }}>
  126. <View style={{ flex: 1 }}>
  127. {renderToolbar()}
  128. <CPDFReaderView
  129. ref={pdfReaderRef}
  130. document={samplePDF}
  131. configuration={ComPDFKit.getDefaultConfig({
  132. toolbarConfig: {
  133. iosLeftBarAvailableActions: [
  134. CPDFToolbarAction.THUMBNAIL
  135. ]
  136. }
  137. })} />
  138. </View>
  139. </SafeAreaView>
  140. </MenuProvider>
  141. );
  142. };
  143. const styles = StyleSheet.create({
  144. toolbar: {
  145. height: 56,
  146. flexDirection: 'row',
  147. alignItems: 'center',
  148. justifyContent: 'flex-start',
  149. backgroundColor: '#FAFCFF',
  150. paddingHorizontal: 4,
  151. },
  152. toolbarButton: {
  153. padding: 8,
  154. },
  155. toolbarTitle: {
  156. flex: 1,
  157. color: 'black',
  158. fontSize: 16,
  159. fontWeight: 'bold',
  160. marginStart: 8
  161. },
  162. menuOption: {
  163. padding: 8,
  164. fontSize: 14,
  165. color: 'black',
  166. },
  167. });
  168. export default CPDFAnnotationsExampleScreen;