En mi aplicación, los usuarios pueden crear nuevas páginas para un PDF agregándolas como objetos a una ArrayList. Luego, la creación de la nueva página es administrada por un bucle for para iterar a través de cada objeto en ArrayList e imprimirlo en una nueva página.

Pero cuando abro el PDF que se ha creado, parece que obtengo una cantidad 'cuadrada' de páginas. por ejemplo, creo 2 páginas, obtengo 4, creo 3 páginas, obtengo 9, etc.

Creo que tiene algo que ver con mi bucle for pero no puedo verlo. ¿Alguien puede echar un vistazo a mi código?

    public class MainActivity extends AppCompatActivity {

private EditText firstEditText;
ArrayList<PDFPageModel> pageModelArrayList = new ArrayList<>();


@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    firstEditText = findViewById(R.id.firstEditText);
    //request permissions (I won't need this part)
    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, PackageManager.PERMISSION_GRANTED);

    //clear array memory each time you onCreate
    pageModelArrayList.clear();
}

public void addObjectToList(View view){
    //create new object
    PDFPageModel pdfPageModel = new PDFPageModel();

    //add stuff to object from edit text and set type
    pdfPageModel.setPageData(firstEditText.getText().toString().trim());
    pdfPageModel.setType("Text");

    pageModelArrayList.add(pdfPageModel);

    Toast.makeText(MainActivity.this, "Text added", Toast.LENGTH_LONG).show();
}

@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void createMyPDF(View view){
    //done in 3 parts
    //1. creation of PDF document, 2. writing to the document, 3. save document to folder

    //1. PDF Document Creation
    PdfDocument pdfDocument = new PdfDocument();

    //2.
    //for loop for ArrayList new page
    for (int i=0; i < pageModelArrayList.size(); i++){
        for(PDFPageModel filledData : pageModelArrayList){
            filledData.getPageData();
            filledData.getType();

            if(filledData.getType() == "Text"){
                //create a page info description
                PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(595, 842, i+1).create();

                //start a page
                PdfDocument.Page page = pdfDocument.startPage(pageInfo);

                //writing to new page
                Paint paint = new Paint();

                //canvas used to write to page, getting object data from inputted text
                String myString = filledData.getPageData();

                //setting where to start text on the page
                int x = 10, y = 25;

                //multi line loop
                for(String line:myString.split("\n")){
                    page.getCanvas().drawText(line, x, y, paint);
                    y+=paint.descent()-paint.ascent();
                }
                //finish page
                pdfDocument.finishPage(page);
            }else {
                Toast.makeText(MainActivity.this, "Object Type not text", Toast.LENGTH_LONG).show();
            }
        }
    }

    //3. saving to folder
    
    String myFilePath = String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS));

    String fileName = "/myNewPDF-TEST.pdf";


    //create folder to be saved in
    File myFile = new File(myFilePath + "/PDFTestStorage");
    if(!myFile.exists()){
        myFile.mkdirs();
    }

    //new file
    File file = new File(myFile, fileName);

    //save document
    try {
        pdfDocument.writeTo(new FileOutputStream(file));
        Toast.makeText(MainActivity.this, "File Created", Toast.LENGTH_LONG).show();
    } catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(MainActivity.this, "Error: File not created", Toast.LENGTH_LONG).show();
    }

    //close pdf doc
    pdfDocument.close();


}
0
BlackMirror 2 ago. 2020 a las 12:40

1 respuesta

La mejor respuesta

Simplemente quitando el bucle for más externo, es decir, reemplazando:

for (int i=0; i < pageModelArrayList.size(); i++){
    for(PDFPageModel filledData : pageModelArrayList){
        filledData.getPageData();
        filledData.getType();

        if(filledData.getType() == "Text"){
            //create a page info description
            PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(595, 842, i+1).create();

            //start a page
            PdfDocument.Page page = pdfDocument.startPage(pageInfo);

            //writing to new page
            Paint paint = new Paint();

            //canvas used to write to page, getting object data from inputted text
            String myString = filledData.getPageData();

            //setting where to start text on the page
            int x = 10, y = 25;

            //multi line loop
            for(String line:myString.split("\n")){
                page.getCanvas().drawText(line, x, y, paint);
                y+=paint.descent()-paint.ascent();
            }
            //finish page
            pdfDocument.finishPage(page);
        }else {
            Toast.makeText(MainActivity.this, "Object Type not text", Toast.LENGTH_LONG).show();
        }
    }
}

Con:

    int i=0;
    for(PDFPageModel filledData : pageModelArrayList){
        filledData.getPageData();
        filledData.getType();

        if(filledData.getType() == "Text"){
            //create a page info description
            PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(595, 842, i+1).create();

            //start a page
            PdfDocument.Page page = pdfDocument.startPage(pageInfo);

            //writing to new page
            Paint paint = new Paint();

            //canvas used to write to page, getting object data from inputted text
            String myString = filledData.getPageData();

            //setting where to start text on the page
            int x = 10, y = 25;

            //multi line loop
            for(String line:myString.split("\n")){
                page.getCanvas().drawText(line, x, y, paint);
                y+=paint.descent()-paint.ascent();
            }
            //finish page
            pdfDocument.finishPage(page);
        }else {
            Toast.makeText(MainActivity.this, "Object Type not text", Toast.LENGTH_LONG).show();
      i++
            }

Debería acercarte un paso más a la solución del problema. Es casi seguro que el comportamiento al cuadrado que está describiendo proviene de bucles anidados.

1
AK. Bab 2 ago. 2020 a las 10:04