G

Mycode

unlisted
Guest Mar 08, 2024 Never 58
Clone
Plaintext UnityCode 330 lines (261 loc) | 11.59 KB
1
using UnityEngine;
2
using UnityEngine.UI;
3
using System.Collections;
4
using iTextSharp.text;
5
using iTextSharp.text.pdf;
6
using System.IO;
7
using SimpleFileBrowser;
8
using Firebase;
9
using Firebase.Database;
10
using Firebase.Extensions;
11
using TMPro;
12
using System;
13
14
public class PDFPDF : MonoBehaviour
15
{
16
public Button generatePDF;
17
public TMP_InputField patientUsernameInput;
18
public TMP_InputField doctorUsernameInput;
19
20
private DatabaseReference databaseReference;
21
22
iTextSharp.text.Document pdfdoc;
23
iTextSharp.text.Image pdfImg;
24
iTextSharp.text.pdf.PdfWriter pdfwriter;
25
iTextSharp.text.Rectangle currentPageSize = PageSize.A4;
26
27
int gridSideLength = 20;
28
int blockRowInterval = 40;
29
int gridCountInBlockRowVertical = 40;
30
int gridCountInBlockRowHorizontal;
31
32
int firstBlockRowOffsetInVertical = 100;
33
int blockRowHeight;
34
int blockRowCount;
35
36
int blockRowIndex = 0;
37
float currentBaseLine;
38
39
int rawDataCountInBlockRow = 0;
40
float rawDataInterval = 0;
41
int rawDataIndex = 0;
42
43
int maxRawData = 13990;
44
float scaledRawData = 0;
45
46
private DataSnapshot userSnapshot;
47
private DataSnapshot exerciseSnapshot;
48
49
void Start()
50
{
51
FirebaseApp.CheckAndFixDependenciesAsync().ContinueWithOnMainThread(task =>
52
{
53
FirebaseApp app = FirebaseApp.DefaultInstance;
54
databaseReference = FirebaseDatabase.DefaultInstance.RootReference;
55
});
56
57
generatePDF.onClick.AddListener(OnGeneratePDFButtonClicked);
58
}
59
60
public void OnGeneratePDFButtonClicked()
61
{
62
GenerateAndSavePDF();
63
}
64
65
private void GenerateAndSavePDF()
66
{
67
string pusername = patientUsernameInput.text;
68
string dusername = doctorUsernameInput.text;
69
70
if (string.IsNullOrEmpty(pusername) || string.IsNullOrEmpty(dusername))
71
{
72
Debug.LogError("Patient or Doctor username is empty.");
73
return;
74
}
75
76
Debug.Log("Fetching user and exercise data from Firebase...");
77
FetchUserInfoFromFirebase(pusername);
78
FetchExercisesFromFirebase(pusername, dusername);
79
80
// Always show the save dialog, even if there are issues with Firebase or input validation
81
ShowSaveDialog(Path.Combine(Application.temporaryCachePath, "tempPDF.pdf"));
82
}
83
84
85
86
private void FetchUserInfoFromFirebase(string pusername)
87
{
88
string userPath = $"Users/Patient Info/{pusername}";
89
90
databaseReference.Child(userPath).GetValueAsync().ContinueWithOnMainThread(task =>
91
{
92
if (task.IsFaulted || task.IsCanceled)
93
{
94
Debug.LogError("Failed to fetch user data from Firebase.");
95
return;
96
}
97
98
userSnapshot = task.Result;
99
100
DataSnapshot snapshot = task.Result;
101
if (snapshot.Exists)
102
{
103
string firstName = snapshot.Child("firstname").Value.ToString();
104
string middleName = snapshot.Child("middleName").Value.ToString();
105
string lastName = snapshot.Child("lastName").Value.ToString();
106
string age = snapshot.Child("age").Value.ToString();
107
string gender = snapshot.Child("gender").Value.ToString();
108
string mobileNumber = snapshot.Child("mobileNumber").Value.ToString();
109
string email = snapshot.Child("email").Value.ToString();
110
111
GeneratePDFWithUserInfo(firstName, middleName, lastName, age, gender, mobileNumber, email);
112
}
113
else
114
{
115
Debug.LogError($"User with username '{pusername}' not found in Firebase.");
116
}
117
});
118
}
119
120
private void FetchExercisesFromFirebase(string pusername, string dusername)
121
{
122
string exercisePath = $"Doctor List/{dusername}/{pusername}/Exercise History";
123
124
databaseReference.Child(exercisePath).GetValueAsync().ContinueWithOnMainThread(task =>
125
{
126
if (task.IsFaulted || task.IsCanceled)
127
{
128
Debug.LogError("Failed to fetch exercise data from Firebase.");
129
return;
130
}
131
132
exerciseSnapshot = task.Result;
133
134
DataSnapshot snapshot = task.Result;
135
if (snapshot.Exists)
136
{
137
foreach (DataSnapshot singleExerciseSnapshot in snapshot.Children)
138
{
139
string exerciseType = singleExerciseSnapshot.Key;
140
141
Debug.Log($"Exercise Type: {exerciseType}");
142
Debug.Log($"Snapshot: {singleExerciseSnapshot.GetRawJsonValue()}");
143
144
PrintExerciseInfoToPDF(exerciseType, singleExerciseSnapshot);
145
}
146
}
147
});
148
}
149
150
private void GeneratePDFWithUserInfo(string firstName, string middleName, string lastName, string age, string gender, string mobileNumber, string email)
151
{
152
pdfdoc = new iTextSharp.text.Document(currentPageSize);
153
154
string tempPDFPath = Path.Combine(Application.temporaryCachePath, "tempPDF.pdf");
155
pdfwriter = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfdoc, new FileStream(tempPDFPath, FileMode.Create));
156
157
pdfdoc.Open();
158
159
160
blockRowCount = gridCountInBlockRowVertical / gridSideLength;
161
blockRowHeight = blockRowCount * gridSideLength;
162
163
AddTitleToPDF("Progress Report");
164
165
pdfdoc.Add(new iTextSharp.text.Paragraph(" "));
166
pdfdoc.Add(new iTextSharp.text.Paragraph(" "));
167
168
var introductionParagraph = new iTextSharp.text.Paragraph();
169
introductionParagraph.Alignment = Element.ALIGN_CENTER;
170
introductionParagraph.Add("This progress report provides an overview of the exercises and repetitions completed by the patient. "
171
+ "It highlights the patient's monthly progress in their rehabilitation journey. aaa"
172
+ "The information presented includes:");
173
174
pdfdoc.Add(introductionParagraph);
175
176
pdfdoc.Add(new iTextSharp.text.Paragraph(" "));
177
178
pdfdoc.Add(new iTextSharp.text.Paragraph(" "));
179
180
AddContentToPDF($"Name: {firstName} {middleName} {lastName}\n" +
181
$"Age: {age}\n" +
182
$"Gender: {gender}\n" +
183
$"Contact Number: {mobileNumber}\n" +
184
$"Email: {email}");
185
186
foreach (DataSnapshot exerciseSnapshot in exerciseSnapshot.Children)
187
{
188
string exerciseType = exerciseSnapshot.Key;
189
190
PrintExerciseInfoToPDF(exerciseType, exerciseSnapshot);
191
}
192
193
FinalizePDF();
194
195
ShowSaveDialog(tempPDFPath);
196
}
197
198
private void PrintExerciseInfoToPDF(string exerciseType, DataSnapshot singleExerciseSnapshot)
199
{
200
pdfdoc.Add(new iTextSharp.text.Paragraph(" "));
201
202
// Create a Chunk with bold formatting
203
iTextSharp.text.Chunk boldChunk = new iTextSharp.text.Chunk($"Type of Exercise: {exerciseType}", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12, iTextSharp.text.Font.BOLD));
204
205
// Add the bold Chunk to the Paragraph
206
iTextSharp.text.Paragraph exerciseTypeParagraph = new iTextSharp.text.Paragraph(boldChunk);
207
208
// Add the Paragraph to the document
209
pdfdoc.Add(exerciseTypeParagraph);
210
211
FetchExerciseDataFromFirebase(exerciseType, singleExerciseSnapshot);
212
}
213
214
215
private void FetchExerciseDataFromFirebase(string exerciseType, DataSnapshot exerciseSnapshot)
216
{
217
Debug.Log($"Fetching exercise data for {exerciseType}...");
218
219
// Fetch data for each child under the exercise type (Date, Level, Reps)
220
DataSnapshot dateData = exerciseSnapshot.Child("Date");
221
DataSnapshot levelData = exerciseSnapshot.Child("Level");
222
DataSnapshot repsData = exerciseSnapshot.Child("Reps");
223
224
if (dateData.HasChildren)
225
{
226
foreach (DataSnapshot dateIndexSnapshot in dateData.Children)
227
{
228
string dateIndex = dateIndexSnapshot.Key;
229
string date = dateIndexSnapshot.Value.ToString();
230
231
// Check if the date index exists in Level and Reps
232
if (levelData.HasChild(dateIndex) && repsData.HasChild(dateIndex))
233
{
234
string level = levelData.Child(dateIndex).Value.ToString();
235
string reps = repsData.Child(dateIndex).Value.ToString();
236
237
Debug.Log($"Debugging: Date: {date}, Level: {level}, Reps: {reps}");
238
239
// Check if the values are not the initial values
240
if (date != "Initial Date Value" && level != "Initial Reps Value" && reps != "Initial Reps Value")
241
{
242
Debug.Log($" Date: {date}");
243
Debug.Log($" Level: {level} Reps: {reps}");
244
245
AddContentToPDF($" Date: {date}");
246
AddContentToPDF($" Level: {level} Reps: {reps}");
247
AddContentToPDF($" ");
248
}
249
}
250
else
251
{
252
Debug.LogError($"Missing data for Date Index: {dateIndex} in Exercise Type: {exerciseType}");
253
}
254
}
255
}
256
else
257
{
258
Debug.LogError($"No Date data found for Exercise Type: {exerciseType}");
259
}
260
}
261
262
263
private void AddTitleToPDF(string title)
264
{
265
var titleFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 16, iTextSharp.text.Font.BOLD);
266
var titleParagraph = new iTextSharp.text.Paragraph(title, titleFont);
267
titleParagraph.Alignment = Element.ALIGN_CENTER;
268
pdfdoc.Add(titleParagraph);
269
}
270
271
private void AddContentToPDF(string content)
272
{
273
var contentFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12);
274
var contentParagraph = new iTextSharp.text.Paragraph(content, contentFont);
275
276
// Check if the content will fit on the current page
277
float remainingSpace = pdfwriter.GetVerticalPosition(true) - pdfdoc.BottomMargin;
278
if (contentParagraph.TotalLeading > remainingSpace)
279
{
280
// If not, start a new page
281
pdfdoc.NewPage();
282
}
283
284
pdfdoc.Add(contentParagraph);
285
}
286
287
288
private void FinalizePDF()
289
{
290
pdfdoc.Close();
291
pdfwriter.Close();
292
pdfdoc.Dispose(); // Add this line to dispose of the pdfdoc object
293
pdfwriter.Dispose(); // Add this line to dispose of the pdfwriter object
294
}
295
296
private void ShowSaveDialog(string tempPDFPath)
297
{
298
// Show the file browser
299
FileBrowser.SetFilters(false, ".pdf");
300
FileBrowser.ShowSaveDialog((paths) =>
301
{
302
if (paths.Length > 0)
303
{
304
// Close and dispose of pdfdoc and pdfwriter
305
FinalizePDF();
306
307
// Copy the temporary PDF file to the selected destination
308
CopyAndDeleteFile(tempPDFPath, paths[0]);
309
}
310
}, null, FileBrowser.PickMode.Files);
311
}
312
313
private void CopyAndDeleteFile(string sourcePath, string destinationPath)
314
{
315
try
316
{
317
// Copy the file to the destination
318
File.Copy(sourcePath, destinationPath, true);
319
Debug.Log($"PDF saved successfully and copied to: {destinationPath}");
320
321
// Delete the temporary file
322
File.Delete(sourcePath);
323
Debug.Log($"Temporary file deleted: {sourcePath}");
324
}
325
catch (Exception e)
326
{
327
Debug.LogError($"Error saving, copying, and deleting file: {e.Message}");
328
}
329
}
330
}