Skip to content

Commit e0e2567

Browse files
Ligia-Andreicachristopherdro
authored andcommitted
Refactor RNHTMLtoPDFModule (#81)
1 parent c8bb3b3 commit e0e2567

File tree

4 files changed

+58
-40
lines changed

4 files changed

+58
-40
lines changed

README.md

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ export default class Example extends Component {
6565
let options = {
6666
html: '<h1>PDF TEST</h1>',
6767
fileName: 'test',
68-
directory: 'docs',
68+
directory: 'Documents',
6969
};
7070

7171
let file = await RNHTMLtoPDF.convert(options)
@@ -91,7 +91,8 @@ export default class Example extends Component {
9191
|---|---|---|---|
9292
| `html` | `string` | | HTML string to be converted
9393
| `fileName` | `string` | Random | Custom Filename excluding .pdf extension
94-
| `base64` | boolean | false | return base64 string of pdf file (not recommended)
94+
| `base64` | `boolean` | false | return base64 string of pdf file (not recommended)
95+
| `directory` | `string` |default cache directory| Directory where the file will be created (`Documents` folder in example above). Please note, on iOS `Documents` is the only custom value that is accepted.
9596

9697

9798
#### iOS Only
@@ -103,7 +104,7 @@ export default class Example extends Component {
103104
| `padding` | number | 10 | Outer padding (points)
104105

105106

106-
##### Android Only
107+
#### Android Only
107108

108109
| Param | Type | Default | Note |
109110
|---|---|---|---|

android/src/main/java/android/print/PdfConverter.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -98,13 +98,13 @@ public void setPdfPrintAttrs(PrintAttributes printAttrs) {
9898
}
9999

100100
public void convert(Context context, String htmlString, File file, boolean shouldEncode, WritableMap resultMap,
101-
Promise promise, String baseURL) {
101+
Promise promise, String baseURL) throws Exception {
102102
if (context == null)
103-
throw new IllegalArgumentException("context can't be null");
103+
throw new Exception("context can't be null");
104104
if (htmlString == null)
105-
throw new IllegalArgumentException("htmlString can't be null");
105+
throw new Exception("htmlString can't be null");
106106
if (file == null)
107-
throw new IllegalArgumentException("file can't be null");
107+
throw new Exception("file can't be null");
108108

109109
if (mIsCurrentlyConverting)
110110
return;

android/src/main/java/com/christopherdro/htmltopdf/RNHTMLtoPDFModule.java

Lines changed: 44 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,24 @@
99
import com.facebook.react.bridge.WritableMap;
1010

1111
import java.io.File;
12+
import java.io.IOException;
1213
import java.util.UUID;
1314

1415
import android.os.Environment;
1516
import android.print.PdfConverter;
1617

1718
public class RNHTMLtoPDFModule extends ReactContextBaseJavaModule {
1819

19-
private final ReactApplicationContext mReactContext;
20+
private static final String HTML = "html";
21+
private static final String FILE_NAME = "fileName";
22+
private static final String DIRECTORY = "directory";
23+
private static final String BASE_64 = "base64";
24+
private static final String BASE_URL = "baseURL";
25+
26+
private static final String PDF_EXTENSION = ".pdf";
27+
private static final String PDF_PREFIX = "PDF_";
28+
29+
private final ReactApplicationContext mReactContext;
2030

2131
public RNHTMLtoPDFModule(ReactApplicationContext reactContext) {
2232
super(reactContext);
@@ -32,57 +42,64 @@ public String getName() {
3242
public void convert(final ReadableMap options, final Promise promise) {
3343
try {
3444
File destinationFile;
35-
String htmlString = options.hasKey("html") ? options.getString("html") : null;
36-
if (htmlString == null) return;
45+
String htmlString = options.hasKey(HTML) ? options.getString(HTML) : null;
46+
if (htmlString == null) {
47+
promise.reject(new Exception("RNHTMLtoPDF error: Invalid htmlString parameter."));
48+
return;
49+
}
3750

3851
String fileName;
39-
if (options.hasKey("fileName")) {
40-
fileName = options.getString("fileName");
52+
if (options.hasKey(FILE_NAME)) {
53+
fileName = options.getString(FILE_NAME);
54+
if (!isFileNameValid(fileName)) {
55+
promise.reject(new Exception("RNHTMLtoPDF error: Invalid fileName parameter."));
56+
return;
57+
}
4158
} else {
42-
fileName = UUID.randomUUID().toString();
59+
fileName = PDF_PREFIX + UUID.randomUUID().toString();
4360
}
4461

45-
if (options.hasKey("directory") && options.getString("directory").equals("docs")) {
62+
if (options.hasKey(DIRECTORY)) {
4663
String state = Environment.getExternalStorageState();
47-
File path = (Environment.MEDIA_MOUNTED.equals(state)) ?
48-
new File(Environment.getExternalStorageDirectory(), Environment.DIRECTORY_DOCUMENTS)
49-
: new File(mReactContext.getFilesDir(), Environment.DIRECTORY_DOCUMENTS);
50-
51-
if (!path.exists()) path.mkdir();
52-
destinationFile = new File(path, fileName + ".pdf");
64+
File path = (Environment.MEDIA_MOUNTED.equals(state)) ?
65+
new File(Environment.getExternalStorageDirectory(), options.getString(DIRECTORY)) :
66+
new File(mReactContext.getFilesDir(), options.getString(DIRECTORY));
67+
68+
if (!path.exists()) {
69+
if (!path.mkdirs()) {
70+
promise.reject(new Exception("RNHTMLtoPDF error: Could not create folder structure."));
71+
return;
72+
}
73+
}
74+
destinationFile = new File(path, fileName + PDF_EXTENSION);
5375
} else {
5476
destinationFile = getTempFile(fileName);
5577
}
5678

5779
convertToPDF(htmlString,
5880
destinationFile,
59-
options.hasKey("base64") && options.getBoolean("base64") == true,
81+
options.hasKey(BASE_64) && options.getBoolean(BASE_64),
6082
Arguments.createMap(),
6183
promise,
62-
options.hasKey("baseURL") ? options.getString("baseURL") : null);
84+
options.hasKey(BASE_URL) ? options.getString(BASE_URL) : null);
6385
} catch (Exception e) {
64-
promise.reject(e.getMessage());
86+
promise.reject(e);
6587
}
6688
}
6789

6890
private void convertToPDF(String htmlString, File file, boolean shouldEncode, WritableMap resultMap, Promise promise,
6991
String baseURL) throws Exception {
70-
try {
7192
PdfConverter.getInstance().convert(mReactContext, htmlString, file, shouldEncode, resultMap, promise, baseURL);
72-
} catch (Exception e) {
73-
throw new Exception(e);
74-
}
7593
}
7694

77-
private File getTempFile(String fileName) throws Exception {
78-
try {
95+
private File getTempFile(String fileName) throws IOException {
7996
File outputDir = getReactApplicationContext().getCacheDir();
80-
File outputFile = File.createTempFile("PDF_" + UUID.randomUUID().toString(), ".pdf", outputDir);
97+
return File.createTempFile(fileName, PDF_EXTENSION, outputDir);
8198

82-
return outputFile;
99+
}
83100

84-
} catch (Exception e) {
85-
throw new Exception(e);
86-
}
101+
private boolean isFileNameValid(String fileName) throws Exception {
102+
return new File(fileName).getCanonicalFile().getName().equals(fileName);
87103
}
88104
}
105+

ios/RNHTMLtoPDF/RNHTMLtoPDF.m

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ - (instancetype)init
8080
_fileName = [[NSProcessInfo processInfo] globallyUniqueString];
8181
}
8282

83-
if (options[@"directory"] && [options[@"directory"] isEqualToString:@"docs"]){
83+
if (options[@"directory"] && [options[@"directory"] isEqualToString:@"Documents"]){
8484
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
8585
NSString *documentsPath = [paths objectAtIndex:0];
8686

@@ -90,11 +90,11 @@ - (instancetype)init
9090
}
9191

9292
if (options[@"base64"] && [options[@"base64"] boolValue]) {
93-
_base64 = true;
93+
_base64 = true;
9494
} else {
95-
_base64 = false;
95+
_base64 = false;
9696
}
97-
97+
9898
if (options[@"height"] && options[@"width"]) {
9999
float width = [RCTConvert float:options[@"width"]];
100100
float height = [RCTConvert float:options[@"height"]];
@@ -139,10 +139,10 @@ - (void)webViewDidFinishLoad:(UIWebView *)awebView
139139

140140
if (pdfData) {
141141
NSString *pdfBase64 = @"";
142-
142+
143143
[pdfData writeToFile:_filePath atomically:YES];
144144
if (_base64) {
145-
pdfBase64 = [pdfData base64EncodedStringWithOptions:0];
145+
pdfBase64 = [pdfData base64EncodedStringWithOptions:0];
146146
}
147147
NSDictionary *data = [NSDictionary dictionaryWithObjectsAndKeys:
148148
pdfBase64, @"base64",

0 commit comments

Comments
 (0)