Creating multiple pages of PDF using android.graphics.pdf - android

I am trying to create an PDF using android.graphics.pdf. My issue is with multiple pages. I can give android.graphics.pdf html which could be then printed to a PDF. Now that doesn't work if text overflows the set page size. Is it possible to give it all the html and it would create multiple pages according to the content with respect to the page size? As does TCPDF :)
Note. I am trying to avoid creating separate multiple pages by calculating the height of the content.

For this you'll need to add the jar of iTextG to your project:
public void createandDisplayPdf(String text) {
Document doc = new Document();
try {
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Dir";
File dir = new File(path);
if(!dir.exists())
dir.mkdirs();
File file = new File(dir, "newFile.pdf");
FileOutputStream fOut = new FileOutputStream(file);
PdfWriter.getInstance(doc, fOut);
//open the document
doc.open();
Paragraph p1 = new Paragraph(text);
Font paraFont= new Font(Font.COURIER);
p1.setAlignment(Paragraph.ALIGN_CENTER);
p1.setFont(paraFont);
//add paragraph to document
doc.add(p1);
} catch (DocumentException de) {
Log.e("PDFCreator", "DocumentException:" + de);
} catch (IOException e) {
Log.e("PDFCreator", "ioException:" + e);
}
finally {
doc.close();
}
viewPdf("newFile.pdf", "Dir");
}
// Method for opening a pdf file
private void viewPdf(String file, String directory) {
File pdfFile = new File(Environment.getExternalStorageDirectory() + "/" + directory + "/" + file);
Uri path = Uri.fromFile(pdfFile);
// Setting the intent for pdf reader
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(pdfIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(TableActivity.this, "Can't read pdf file", Toast.LENGTH_SHORT).show();
}
}

Related

How to Use URL by replacing File Storage path in Android

I am Printing Pdf using Google Cloud Printing from my Storage of my phone. i want to use pdf URL by replacing this. How to use URL?
For Example: i want to replace /print/test.pdf" to "www.example.com/print/test.pdf"
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/print/test.pdf");
Intent printIntent = new Intent(MainActivity.this,PrintDialogActivity.class);
printIntent.setDataAndType(Uri.fromFile(file),"application/pdf");
printIntent.putExtra("title", "Android print demo");
startActivity(printIntent);
Download http://central.maven.org/maven2/commons-io/commons-io/2.4/commons-io-2.4.jar and paste it to your libs folder in Android Studio. Open your Gradle file and inside the dependencies add this "compile files('libs/commons-io-1.3.2.jar')"
URL url = null;
try {
url = new URL("http://www.cbu.edu.zm/downloads/pdf-sample.pdf");
} catch (MalformedURLException e) {
e.printStackTrace();
}
String tDir = System.getProperty("java.io.tmpdir");
String path = tDir + "tmp" + ".pdf";
File file = new File(path); file.deleteOnExit();
try {
FileUtils.copyURLToFile(url, file);
} catch (IOException e) {
e.printStackTrace();
}
Intent printIntent = new Intent(MainActivity.this,
PrintDialogActivity.class);
printIntent.setDataAndType(Uri.fromFile(file),
"application/pdf");
printIntent.putExtra("title", "Android print demo");
startActivity(printIntent);

How does appear saved SD card images in Android's Gallery?

I save an image to the sdcard and it doesn't appear in the Phone's Gallery. I can see saved image in a folder, but it folder doesn't apper in gallery.
My codes here, how fix it?
img_icon.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
img_resim.buildDrawingCache();
Bitmap bm = img_resim.getDrawingCache();
OutputStream fOut = null;
Uri outputFileUri;
try {
root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "folder_name" + File.separator);
root.mkdirs();
File sdImageMainDirectory = new File(root, "myPicName.jpg");
outputFileUri = Uri.fromFile(sdImageMainDirectory);
fOut = new FileOutputStream(sdImageMainDirectory);
} catch (Exception e) {
Toast.makeText(context.getActivity(),
"Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
}
try {
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
}
context.getActivity()
.sendBroadcast(
new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
Uri.parse("file://"
+ Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES))));
return true;
}
});
return rowView;
}
Thanks for helping..
Your problem lies here:
context.getActivity()
.sendBroadcast(
new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
Uri.parse("file://"
+ Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES))));
You are asking Android to re-index all of the files in Environment.DIRECTORY_PICTURES.
Asking to scan a whole directory tree is wasteful. In your case, it it even more wasteful, since you are not writing your file to that directory. Instead, you are writing that file to:
root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "folder_name" + File.separator);
root.mkdirs();
File sdImageMainDirectory = new File(root, "myPicName.jpg");
Hence, your scan will not pick up this file, which you are writing to some random spot on external storage.
You need to decide the proper place to store your file, then index that one file.

The method getInstance(byte[]) is undefined for the type Document.. Android

I am generating pdf using droidText liberary
I have the following code
public void createPDF()
{
Document doc = new Document();
try {
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/droidText";
File dir = new File(path);
if(!dir.exists()){
System.out.println("directory not exists");
dir.mkdirs();
}else{
System.out.println("directory exirsts");
}
System.out.println("path="+path);
Log.d("PDFCreator", "PDF Path: " + path);
File file = new File(dir, "sample.pdf");
FileOutputStream fOut = new FileOutputStream(file);
PdfWriter.getInstance(doc, fOut);
//open the document
doc.open();
Paragraph p1 = new Paragraph("Hi! I am generating my first PDF using DroidText");
Font paraFont= new Font(Font.COURIER);
p1.setAlignment(Paragraph.ALIGN_CENTER);
p1.setFont(paraFont);
//add paragraph to document
doc.add(p1);
Paragraph p2 = new Paragraph("This is an example of a simple paragraph");
Font paraFont2= new Font(Font.COURIER,14.0f,Color.GREEN);
p2.setAlignment(Paragraph.ALIGN_CENTER);
p2.setFont(paraFont2);
doc.add(p2);
//
//set footer
Phrase footerText = new Phrase("This is an example of a footer");
HeaderFooter pdfFooter = new HeaderFooter(footerText, false);
doc.setFooter(pdfFooter);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),"application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
} catch (DocumentException de) {
Log.e("PDFCreator", "DocumentException:" + de);
} catch (IOException e) {
Log.e("PDFCreator", "ioException:" + e);
}
finally
{
doc.close();
}
}
it works.. but when I add Image to it using following lines, it says "The method getInstance(byte[]) is undefined for the type Document"
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeResource(getBaseContext().getResources(), R.drawable.ic_launcher);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100 , stream);
Image myImg = Image.getInstance(stream.toByteArray());
//myImg.setAlignment(Image.MIDDLE);
add image to document
doc.add(myImg);
help me in adding images to the document
As per Document.java, that class doesn't have a getInstance method.
You want Image.getInstance as per this StackOverflow question,
E.g.
Image myImg = Image.getInstance(stream.toByteArray());
doc.add(myImg);
which isn't a duplicate question but does have an answer which answers your statement of "help me in adding images to the document"

Fail to Write PDF In Emulator SDCard

I am using itext library , i am not able to write pdf in emulator sdcard even though i code seem from my point of view what is problem i could not find out and yes i have also add the write external storage permission. It give me file not found exception ,
try
{
String path = Environment.getExternalStorageDirectory()+"/Hello/";
File file = new File(path+"hello.pdf");
System.out.println(file.toString());
if(!file.exists()){
file.getParentFile().mkdirs();
try {
file.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block e.printStackTrace(); }
}
}
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(Environment.getExternalStorageDirectory()
+File.separator
+"Hello" //folder name
+File.separator
+"hello.pdf"));
document.open();
document.add(new Paragraph("hello"));
document.close();
File path = new File (Environment.getExternalStorageDirectory(),"Hello");
if (!path.exists()) {
path.mkdir();
}
File file = new File(path, "hello.pdf");
System.out.println(file.toString());
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(file);
document.open();
document.add(new Paragraph("hello");
document.close();

How to create text file and insert data to that file on Android

How can I create file.txt and insert data on file with content of some of variable on my code for example : population [][]; on Android, so there will be folder files on our package in file explorer (data/data/ourpackage/files/ourfiles.txt) Thank You
Using this code you can write to a text file in the SDCard.
Along with it, you need to set a permission in the Android Manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
This is the code :
public void generateNoteOnSD(Context context, String sFileName, String sBody) {
try {
File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
Before writing files you must also check whether your SDCard is mounted & the external storage state is writable.
Environment.getExternalStorageState()
Check the android documentation. It's in fact not much different than standard java io file handling so you could also check that documentation.
An example from the android documentation:
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
If you want to create a file and write and append data to it many times, then use the below code, it will create file if not exits and will append data if it exists.
SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd");
Date now = new Date();
String fileName = formatter.format(now) + ".txt";//like 2016_01_12.txt
try
{
File root = new File(Environment.getExternalStorageDirectory()+File.separator+"Music_Folder", "Report Files");
//File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists())
{
root.mkdirs();
}
File gpxfile = new File(root, fileName);
FileWriter writer = new FileWriter(gpxfile,true);
writer.append(sBody+"\n\n");
writer.flush();
writer.close();
Toast.makeText(this, "Data has been written to Report File", Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
}
First create a Project With PdfCreation in Android Studio
Then Follow below steps:
1.Download itextpdf-5.3.2.jar library from this link [https://sourceforge.net/projects/itext/files/iText/iText5.3.2/][1] and then
2.Add to app>libs>itextpdf-5.3.2.jar
3.Right click on jar file then click on add to library
4. Document document = new Document(PageSize.A4); // Create Directory in External Storage
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/PDF");
System.out.print(myDir.toString());
myDir.mkdirs(); // Create Pdf Writer for Writting into New Created Document
try {
PdfWriter.getInstance(document, new FileOutputStream(FILE));
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} // Open Document for Writting into document
document.open(); // User Define Method
addMetaData(document);
try {
addTitlePage(document);
} catch (DocumentException e) {
e.printStackTrace();
} // Close Document after writting all content
document.close();
5. public void addMetaData(Document document)
{
document.addTitle("RESUME");
document.addSubject("Person Info");
document.addKeywords("Personal, Education, Skills");
document.addAuthor("TAG");
document.addCreator("TAG");
}
public void addTitlePage(Document document) throws DocumentException
{ // Font Style for Document
Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD);
Font titleFont = new Font(Font.FontFamily.TIMES_ROMAN, 22, Font.BOLD
| Font.UNDERLINE, BaseColor.GRAY);
Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);
Font normal = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.NORMAL); // Start New Paragraph
Paragraph prHead = new Paragraph(); // Set Font in this Paragraph
prHead.setFont(titleFont); // Add item into Paragraph
prHead.add("RESUME – Name\n"); // Create Table into Document with 1 Row
PdfPTable myTable = new PdfPTable(1); // 100.0f mean width of table is same as Document size
myTable.setWidthPercentage(100.0f); // Create New Cell into Table
PdfPCell myCell = new PdfPCell(new Paragraph(""));
myCell.setBorder(Rectangle.BOTTOM); // Add Cell into Table
myTable.addCell(myCell);
prHead.setFont(catFont);
prHead.add("\nName1 Name2\n");
prHead.setAlignment(Element.ALIGN_CENTER); // Add all above details into Document
document.add(prHead);
document.add(myTable);
document.add(myTable); // Now Start another New Paragraph
Paragraph prPersinalInfo = new Paragraph();
prPersinalInfo.setFont(smallBold);
prPersinalInfo.add("Address 1\n");
prPersinalInfo.add("Address 2\n");
prPersinalInfo.add("City: SanFran. State: CA\n");
prPersinalInfo.add("Country: USA Zip Code: 000001\n");
prPersinalInfo.add("Mobile: 9999999999 Fax: 1111111 Email: john_pit#gmail.com \n");
prPersinalInfo.setAlignment(Element.ALIGN_CENTER);
document.add(prPersinalInfo);
document.add(myTable);
document.add(myTable);
Paragraph prProfile = new Paragraph();
prProfile.setFont(smallBold);
prProfile.add("\n \n Profile : \n ");
prProfile.setFont(normal);
prProfile.add("\nI am Mr. XYZ. I am Android Application Developer at TAG.");
prProfile.setFont(smallBold);
document.add(prProfile); // Create new Page in PDF
document.newPage();
}
I'm using Kotlin here
Just adding the information in here, you can also create readable file outside Private Directory for the apps by doing this example
var teks="your teks"
var NamaFile="Text1.txt"
var strwrt:FileWriter
strwrt=FileWriter(File("sdcard/${NamaFile}"))
strwrt.write(teks)
strwrt.close()
after that, you can access File Manager and look up on the Internal Storage. Text1.txt will be on there below all the folders.

Categories

Resources