/*
 * SDK Pullenti Unitext, version 4.33, fabruary 2026. Copyright (c) 2013-2026, Pullenti. All rights reserved. 
 * Non-Commercial Freeware and Commercial Software. 
 * This class is generated using the converter Unisharping (www.unisharping.ru) from Pullenti C# project. 
 * The latest version of the code is available on the site www.pullenti.ru
 */

package com.pullenti.unitext.internal.pdf;

/**
 * Работа с PDF
 */
public class PdfHelper {

    public static com.pullenti.unitext.UnitextDocument createUni(String pdfFileName, byte[] fileContent, com.pullenti.unitext.CreateDocumentParam pars) {
        java.util.ArrayList<com.pullenti.unitext.UnilayPage> pages = new java.util.ArrayList<com.pullenti.unitext.UnilayPage>();
        com.pullenti.unitext.UnitextDocument doc = com.pullenti.unitext.UnitextDocument._new47(com.pullenti.unitext.FileFormat.PDF);
        try {
            try (PdfFile file = new PdfFile()) {
                file.open(pdfFileName, fileContent);
                if (file.encrypt != null) 
                    doc.errorMessage = "Can't extract pages from encrypted pdf";
                if (file.rootObject != null) {
                    PdfDictionary mt = file.rootObject.getDictionary("Metadata", null);
                    if (mt != null) {
                        byte[] dat = mt.extractData();
                        if (dat != null) {
                            try {
                                String str = com.pullenti.unisharp.Utils.decodeCharset(java.nio.charset.Charset.forName("UTF-8"), dat, 0, -1);
                                int i = str.indexOf("?>");
                                if (i > 0) 
                                    str = str.substring(i + 2).trim();
                                com.pullenti.unisharp.XmlDocumentWrapper xml = new com.pullenti.unisharp.XmlDocumentWrapper();
                                xml.doc = xml.db.parse(new org.xml.sax.InputSource(new java.io.StringReader(str)));
                                _readMetadata0(doc, xml.doc.getDocumentElement(), null);
                            } catch (Exception ex228) {
                            }
                        }
                    }
                }
                if (file.info != null) {
                    String str = file.info.getStringItem("Title");
                    if (!com.pullenti.unisharp.Utils.isNullOrEmpty(str) && !doc.attrs.containsKey("title")) 
                        doc.attrs.put("title", str);
                    str = file.info.getStringItem("Author");
                    if (!com.pullenti.unisharp.Utils.isNullOrEmpty(str) && !doc.attrs.containsKey("author")) 
                        doc.attrs.put("author", str);
                }
                for (int ii = 0; ii < file.pages.size(); ii++) {
                    if (pars != null) 
                        pars.progress((ii * 100) / file.pages.size());
                    PdfDictionary pdic = file.pages.get(ii);
                    PdfPage pPage = new PdfPage(pdic, null, false, false);
                    com.pullenti.unitext.UnilayPage up = new com.pullenti.unitext.UnilayPage();
                    up.width = (int)pPage.getWidth();
                    up.height = (int)pPage.getHeight();
                    pages.add(up);
                    up.number = pages.size();
                    java.util.ArrayList<com.pullenti.unitext.UnilayRectangle> imgs = new java.util.ArrayList<com.pullenti.unitext.UnilayRectangle>();
                    for (PdfRect it : pPage.items) {
                        if (it instanceof PdfFig) 
                            continue;
                        com.pullenti.unitext.UnilayRectangle r = new com.pullenti.unitext.UnilayRectangle();
                        r.left = it.getLeft();
                        r.top = it.getTop();
                        r.right = it.getRight();
                        r.bottom = it.getBottom();
                        r.page = up;
                        if (it instanceof PdfText) 
                            r.text = ((PdfText)com.pullenti.unisharp.Utils.cast(it, PdfText.class)).text;
                        else if (it instanceof PdfImage) {
                            r.imageContent = ((PdfImage)com.pullenti.unisharp.Utils.cast(it, PdfImage.class)).content;
                            r.tag = it;
                            imgs.add(r);
                        }
                        up.rects.add(r);
                    }
                    if (up.imageContent == null && imgs.size() > 0 && imgs.get(0).imageContent != null) {
                        boolean ok = up.rects.size() == 1;
                        if (!ok || imgs.size() > 1) {
                            if (Math.abs((((imgs.get(0).right - imgs.get(0).left - ((double)up.width))) / ((double)up.width))) < 0.2) 
                                ok = true;
                        }
                        if (ok) {
                            up.imageContent = imgs.get(0).imageContent;
                            up.rects.remove(imgs.get(0));
                        }
                    }
                }
            }
        } catch (Exception ex) {
            doc.errorMessage = ex.getMessage();
            return doc;
        }
        if (pages == null || pages.size() == 0 || doc.errorMessage != null) {
            if (doc.errorMessage == null) 
                doc.errorMessage = "Can't extract pages from pdf-file";
            return doc;
        }
        doc.pages = pages;
        com.pullenti.unitext.internal.uni.UnilayoutHelper.createContentFromPages(doc, false);
        com.pullenti.unitext.UnitextContainer cnt = (com.pullenti.unitext.UnitextContainer)com.pullenti.unisharp.Utils.cast(doc.content, com.pullenti.unitext.UnitextContainer.class);
        if (cnt == null) 
            return doc;
        for (int i = 0; i < cnt.children.size(); i++) {
            com.pullenti.unitext.UnitextPlaintext pt = (com.pullenti.unitext.UnitextPlaintext)com.pullenti.unisharp.Utils.cast(cnt.children.get(i), com.pullenti.unitext.UnitextPlaintext.class);
            if (pt == null) 
                continue;
            if (!pt.isWhitespaces()) 
                continue;
            if (i == 0 || (cnt.children.get(i - 1) instanceof com.pullenti.unitext.UnitextNewline) || (cnt.children.get(i - 1) instanceof com.pullenti.unitext.UnitextPagebreak)) {
            }
            else 
                continue;
            if ((i + 1) == cnt.children.size() || (cnt.children.get(i + 1) instanceof com.pullenti.unitext.UnitextNewline) || (cnt.children.get(i + 1) instanceof com.pullenti.unitext.UnitextPagebreak)) {
            }
            else 
                continue;
            cnt.children.remove(i);
            i--;
        }
        doc.content = doc.content.optimize(true, null);
        return doc;
    }

    private static void _readMetadata0(com.pullenti.unitext.UnitextDocument doc, org.w3c.dom.Node xml, String typ) {
        for (org.w3c.dom.Node x : (new com.pullenti.unisharp.XmlNodeListWrapper(xml.getChildNodes())).arr) {
            if (com.pullenti.unisharp.Utils.stringsEq(com.pullenti.unisharp.Utils.getXmlLocalName(x), "title")) 
                _readMetadata0(doc, x, "title");
            else if (com.pullenti.unisharp.Utils.stringsEq(com.pullenti.unisharp.Utils.getXmlLocalName(x), "creator")) 
                _readMetadata0(doc, x, "author");
            else if (com.pullenti.unisharp.Utils.stringsEq(com.pullenti.unisharp.Utils.getXmlLocalName(x), "subject")) 
                _readMetadata0(doc, x, "subject");
            else if (com.pullenti.unisharp.Utils.stringsEq(com.pullenti.unisharp.Utils.getXmlLocalName(x), "Keywords")) {
                String val = x.getTextContent();
                if (!com.pullenti.unisharp.Utils.isNullOrEmpty(val) && !doc.attrs.containsKey("keywords")) 
                    doc.attrs.put("keywords", val);
            }
            else if (typ != null && com.pullenti.unisharp.Utils.stringsEq(com.pullenti.unisharp.Utils.getXmlLocalName(x), "li") && !com.pullenti.unisharp.Utils.isNullOrEmpty(x.getTextContent())) {
                String txt = x.getTextContent();
                if (!doc.attrs.containsKey(typ)) 
                    doc.attrs.put(typ, txt);
                else 
                    doc.attrs.put(typ, (doc.attrs.get(typ) + "; " + txt));
            }
            else 
                _readMetadata0(doc, x, typ);
        }
    }
    public PdfHelper() {
    }
}
