2016年12月28日水曜日

[Android]How to make a PDF from an image

さて、今回はAndroidで画像からPDFを作成する方法についてご説明します。
I explain how to make a PDF from an image on Android this time.

環境(Environment): Android Studio 2.2.1, API 21

今回もまずはサンプルコードから。
At first, look sample code below.


private void savePDFTmp(Bitmap bmpPrint){
    File cachedir = getExternalCacheDir();
    String path = cachedir.getPath() + "/sample.pdf";
    File saveFile = new File(path);

    PdfDocument document = new PdfDocument();

    PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(bmpPrint.getWidth(), bmpPrint.getHeight(), 1).create();

    PdfDocument.Page page = document.startPage(pageInfo);
    Canvas canvas = page.getCanvas();
    canvas.drawBitmap(bmpPrint, 0, 0, null);

    document.finishPage(page);

    try{
        FileOutputStream out = new FileOutputStream(path);
        document.writeTo(out);
        rtnValue = path;
    }catch(Exception e){
        String err = e.toString();
    }
}

AndroidでPDFを作成するにはPdfDocument(android.graphics.pdf.PdfDocument)を使用します。
まず最初にPdfDocument.PageInfoでPDFのページの大きさを定義し、PdfDocumentのstartPageメソッドの引数として設定し、PdfDocument.Pageを取得します。
その後、PdfDocument.Pageに書き込む為のCanvasを取得し、そのCanvasにBitmapを書き込みます。
最後にPdfDocumentのfinishPageメソッドを実行してPDFの書き込みを終了し、FileOutputStreamでファイルとして出力すれば完成です。
Use PdfDocument(android.graphics.pdf.PdfDocument) for making a PDF on Android.
At first, use PdfDocument.PageInfo and specify the scale of a PDF page, and set it to PdfDocument's startPage method as argument, and get PdfDocument.Page.
And get Canvas for writing PdfDocument.Page and draw Bitmap to this Canvas.
At last, declare PdfDocument's finishPage method in order to finish to write a PDF, and use FileOutputStream and write a PDF data to a file.

[関連記事(Articles)]
[iOS]How to make a PDF from an image


にほんブログ村 ライフスタイルブログ クリエイティブライフへ
にほんブログ村

クリエイティブライフ ブログランキングへ

2016年12月27日火曜日

[iOS]How to make a PDF from an image

さて、今回はiOSにて画像からPDFを作成する方法についてご説明します。
I explain how to make a PDF from an image on iOS this time.

環境(Environment):Xcode 8.2.1, Swift 3


まずコードから。

At first, look sample code below.


func makePDF(image:UIImage){
            //Make PDF Data
            var data:NSMutableData! = NSMutableData()
            UIGraphicsBeginPDFContextToData(data,CGRect.zero , nil)
            UIGraphicsBeginPDFPageWithInfo(CGRect(x: 0,y: 0,width: image.size.width,height: image.size.height),nil)
            image.draw(in: CGRect(x: 0,y: 0,width: image.size.width,height: image.size.height))
            UIGraphicsEndPDFContext()
        
            let pickerCtl = MFMailComposeViewController()
            pickerCtl.mailComposeDelegate = self
            pickerCtl.setMessageBody("", isHTML: false)
            pickerCtl.addAttachmentData(data as Data, mimeType: "application/pdf", fileName: pdfTitle2 + ".pdf")
            
            self.present(pickerCtl,animated:true,completion:nil)
            data = nil

        }

まずUIGraphicsBeginPDFContextToDataNSMutableDataに対するPDF用のグラフィックコンテキストを作成します。その後、UIGraphicsBeginPDFPageWithInfoでPDFのページの大きさを定義します。
そしてUIImageの書き込みを行います。
最後にUIGraphicsEndPDFContextを宣言してグラフィックコンテキストを閉じれば完成です。
これでNSMutableDataはPDFのデータとなっています。
このサンプルでは最後にメールに添付して送信できる様にしています。
Use UIGraphicsBeginPDFContextToData and create a PDF-based graphics context that targets the specified NSMutableData. And use UIGraphicsBeginPDFPageWithInfo and specify the scale of a PDF page.
And draw UIImage to NUMutableData.
At last, declare UIGraphicsEndPDFContext and NSMutableData turns into a PDF data.
In this sample code, a PDF Data is send as a E-mail attachment.

[関連記事(Articles)]
[Android]How to make a PDF from an image

にほんブログ村 ライフスタイルブログ クリエイティブライフへ
にほんブログ村

クリエイティブライフ ブログランキングへ

2016年12月26日月曜日

[iOS]How to print and share image

今回はiOSで画像を印刷したり、画像をTwitter、Facebook等の他のアプリと連携する方法についてご説明します。
I write how to print and share image with other applications, for example, Twitter and Facebook, on iOS this time.

iOSの場合は、iOSのApp Extensionsと連携することによって実現します。(画像はPocket Noteでの実施例です。)
In case of iOS, you can cooperate with iOS's App Extensions.(Photographs below are examples of Pocket Note)




環境(Environment):Xcode 8.、Swift 3

早速コードです。UIActivityViewControllerを使用して、App Extensionsに画像を渡します。
This is sample code. Use UIActivityController and you can give an image App Extensions.


let _buttonPrint:UIButton = UIButton()

override func viewDidLoad() {
     super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
     _buttonPrint.frame = CGRect(x: 10,y: 10,width: 40,height: 40)
        _buttonPrint.addTarget(self, action: #selector(MainViewController.TouchUpButtonPrint), for: .touchUpInside)
       self.view.addSubview(_buttonPrint)
}

func TouchUpButtonPrint(){
        // 印刷する画像を取得(Get image for printing)
        var printImage:UIImage! = GetPrintImage()

        let activityViewController = UIActivityViewController(activityItems:[printImage],applicationActivities:nil)
        activityViewController.modalPresentationStyle = UIModalPresentationStyle.popover
        activityViewController.preferredContentSize = CGSize(width: 500,height: 500)
        
        let popoverController = activityViewController.popoverPresentationController
        popoverController?.delegate = self
        popoverController?.permittedArrowDirections = UIPopoverArrowDirection.up
        popoverController?.sourceView = _buttonPrint
        popoverController?.sourceRect = _buttonPrint.bounds
        
        self.present(activityViewController, animated: true, completion: nil)
        
        printImage = nil

    }


[関連記事(Articles)]
[Android]How to print and share image


にほんブログ村 ライフスタイルブログ クリエイティブライフへ
にほんブログ村

クリエイティブライフ ブログランキングへ

2016年12月25日日曜日

[Android]How to print and share image

さて、久々のプログラミングネタです。
今回はAndroidアプリにおいて、Pocket Noteの様に画像を印刷したり、他のアプリに画像を連携したりする方法についてご説明します。
I write method of programming after a long time.
I explain how to print image and share image with other applications on Android application like Pocket Note this time.






環境(Environment):Android Studio 2.2.1 、API 21

1. 印刷(Print)
Androidでは4.4(API 19)から印刷機能がサポートされています。
Androidアプリから印刷を実行するにはPrintHelper(android.support.v4. print.PrintHelper)を使用します。
Android supports print function from Version 4.4(API 19).
Use PrintHelper(android.support.v4. print.PrintHelper) to print image from an Android application.


private void execPrint(Bitmap bmpPrint){
    
    if (PrintHelper.systemSupportsPrint()) {
           PrintHelper printHelper = new PrintHelper(this);
           printHelper.setColorMode(PrintHelper.COLOR_MODE_COLOR);
           printHelper.setScaleMode(PrintHelper.SCALE_MODE_FIT);
           printHelper.printBitmap("Image Title", bmpPrint);
    }
}

2.他アプリとの連携
Android上にインストールされているTwitter,Facebook,Google+等のアプリに画像を連携するにはIntent(android.content.Intent)を使用します。
Use Intent(android.content.Intent) to share image with other applications,for example,Twitter,Facebook and Google+ on Android.

また事前に画像をキャッシュ領域にファイルとして保存してから連携しています。
And save image as file into cache directory before using Intent.


private void execPrint(Bitmap bmpPrint,int applicationType){
    
    if (applicationType == 3 || applicationType == 4){
       Uri saveFileUri = saveTemp2(bmpPrint);
    }else{
       String saveFileName = saveTemp(bmpPrint);
    }

    switch (applicationType){ 
    case 1:
        //Twitter
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.setPackage("com.twitter.android");
        intent.setType("image/jpg");
        File sendFile = new File(saveFileName);
        intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(sendFile));
        startActivity(intent);
        break;
    case 2:
        //facebook
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.setPackage("com.facebook.katana");
        intent.setType("image/jpg");
        File sendFile = new File(saveFileName);
        intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(sendFile));
        startActivity(intent);
        break;
    case 3:
        //Google+
        Intent shareIntent = new PlusShare.Builder(this)
                .addStream(saveFileUri)
                .setType("image/jpg")
                .getIntent();

        startActivityForResult(shareIntent, 0);
        break;
    case 3:
        //Other Applications        Intent share = new Intent(Intent.ACTION_SEND);
        share.setType("image/jpg");
        share.putExtra(Intent.EXTRA_STREAM, saveFileUri);
        startActivity(Intent.createChooser(share, "Share applications"));
        break;
     }
}

//Save image as file and return file's name
private String saveTemp(Bitmap bmpPrint){
    String rtnValue = "";
    File internalCachedir = getExternalCacheDir();

    String path = internalCachedir.getPath() + "/Temp.jpg";
    File saveFile = new File(path);
    FileOutputStream out = new FileOutputStream(path);
    bmpPrint.compress(Bitmap.CompressFormat.JPEG,100,out);
    out.flush();
    out.close();
    return path;
}

//Save image as file and return file's Uri
private Uri saveTemp2(Bitmap bmpPrint){
    File internalCachedir = getExternalCacheDir();

    String path = internalCachedir.getPath() + "/Temp.jpg";
    File saveFile = new File(path);
    FileOutputStream out = new FileOutputStream(path);
    bmpPrint.compress(Bitmap.CompressFormat.JPEG,100,out);
    out.flush();
    out.close();
    
    return Uri.fromFile(saveFile);
}

[関連記事(Articles)]
[iOS]How to print and share image

にほんブログ村 ライフスタイルブログ クリエイティブライフへ
にほんブログ村

クリエイティブライフ ブログランキングへ