【问题标题】:Create Multipage PDF directly from UiTextView in Ipad直接从 Ipad 中的 UiTextView 创建多页 PDF
【发布时间】:2013-02-10 13:16:26
【问题描述】:

我创建了具有特定布局的 pdf。问题是当文本视图的内容很长时,Pdf 不会自动生成新页面,我无法预定义在运行时将创建多少页。谁能帮帮我?

【问题讨论】:

  • ..首先欢迎,,你必须尝试吗??
  • 你有没有这样尝试过,你做过吗

标签: objective-c pdf-generation


【解决方案1】:

很多用户都在搜索此代码以兼容 SWIFT 版本。所以这里适用于 swift 4 和 5。

// PDF 名称并在本地路径生成:

func writeToPDF(filenameStr:String)

{
    pageSize = CGSize.init(width: 768, height: 10000)

   // let fileName: NSString = "test.pdf"
    let fileName = String.init(format: "%@.pdf", filenameStr)
    let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
    let pdfPathWithFileName =   documentDirectory.appending("/" + fileName)//  documentDirectory.appending(fileName as String)
    self.PdfGeneration(filePath: pdfPathWithFileName)

    //lines written to get the document directory path for the generated pdf file.
    if let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.path {
        print("documentsPath",documentsPath)
        // “var/folder/…/documents ” copy the full path

    }


}

//生成pdf文件的方法,显示pdf文件中的文字和图片。

func PdfGeneration(filePath: String)
{
// Prepare the text using a Core Text Framesetter.
//CFAttributedStringRef currentText = CFAttributedStringCreate(NULL, (__bridge CFStringRef)txtObj.text, NULL);
let currentText = CFAttributedStringCreate(nil, (self.textVW_file.text as? CFString?)!, nil)
if(currentText != nil)
{
let framesetter = CTFramesetterCreateWithAttributedString(currentText!)
if (framesetter !=  nil) {
UIGraphicsBeginPDFContextToFile(filePath, .zero, nil)
    var currentRange = CFRangeMake(0, 0)
    var currentPage = 0
    var done = false

repeat {
 repeat {
UIGraphicsBeginPDFPageWithInfo(CGRect.init(x:0, y:0, width:612, height:792), nil)
currentPage = currentPage + 1
self.drawPageNumber(currentPage)
currentRange = self.renderPage(currentPage, withTextRange: currentRange, andFramesetter: framesetter)
let aText:CFAttributedString = currentText!
    print("currentText %@",currentText!)
    print("currentRange.location %@ and %@",currentRange.location,CFAttributedStringGetLength(aText))
if (currentRange.location == CFAttributedStringGetLength(aText)) {
done = true
}
}while (!done)
 UIGraphicsEndPDFContext()
}
else
{
print("Could not create the framesetter needed to lay out the atrributed string.")
}
}
else
{
print("Could not create the framesetter needed to lay out the atrributed string.")

}


}

// 使用Core Text在页面的框架中绘制文本。

func renderPage(_ pageNum: Int, withTextRange currentRange: CFRange, andFramesetter framesetter: CTFramesetter?) -> CFRange {
    var currentRangeIn:CFRange
let currentContext = UIGraphicsGetCurrentContext()
currentContext?.textMatrix = .identity
let frameRect = CGRect(x: 72, y: 72, width: 468, height: 648)
let framePath = CGMutablePath()
framePath.addRect(frameRect, transform: .identity)
    let frameRef = CTFramesetterCreateFrame(framesetter!, currentRange, framePath, nil)
currentContext?.translateBy(x: 0, y: 792)
currentContext?.scaleBy(x: 1.0, y: -1.0)
    CTFrameDraw(frameRef, currentContext!)
currentRangeIn = currentRange
 currentRangeIn = CTFrameGetVisibleStringRange(frameRef)
currentRangeIn.location += currentRange2.length
currentRangeIn.length = 0
return currentRangeIn
}

//并在底部绘制页码

func drawPageNumber(_ pageNum: Int) {
    let pageString = "Page \(pageNum)"
    let theFont = UIFont.systemFont(ofSize: 12)
    let maxSize = CGSize(width: 612, height: 72)
    let pageStringSize: CGSize = pageString.size(withAttributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14.0)])

    //let pageStringSize = pageString.size(with: theFont, constrainedTo: maxSize, lineBreakMode: [])
    let stringRect = CGRect(x: (612.0 - pageStringSize.width) / 2.0, y: 720.0 + ((72.0 - pageStringSize.height) / 2.0), width: pageStringSize.width, height: pageStringSize.height)
    pageString.draw(in: stringRect, withAttributes: [NSAttributedString.Key.font : theFont])
}

【讨论】:

    【解决方案2】:

    您可以尝试使用此代码,这可能会对您有所帮助 在界面生成器中保留一个文本视图和一个按钮,并使用按钮操作方法并生成 pdf 导入这些框架

    #import <QuartzCore/QuartzCore.h>
    #import <CoreText/CoreText.h>
    
    
    
        -(NSString*)getPDFFileName
        {
            NSString* fileName = @"sample.PDF";
            NSArray *arrayPaths =
            NSSearchPathForDirectoriesInDomains(
                                                NSDocumentDirectory,
                                                NSUserDomainMask,
                                                YES);
            NSString *path = [arrayPaths objectAtIndex:0];
            NSString* pdfFileName = [path stringByAppendingPathComponent:fileName];
            return pdfFileName;
    
        }
        -(IBAction)PdfGeneration:(id)sender{
            // Prepare the text using a Core Text Framesetter.
            CFAttributedStringRef currentText = CFAttributedStringCreate(NULL, (__bridge CFStringRef)txtObj.text, NULL);
            if (currentText) {
                    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(currentText);
                    if (framesetter) {
    
                    NSString *pdfFileName = [self getPDFFileName];
    
                    // Create the PDF context using the default page size of 612 x 792.
    
                    UIGraphicsBeginPDFContextToFile(pdfFileName, CGRectZero, nil);
                    CFRange currentRange = CFRangeMake(0, 0);
                    NSInteger currentPage = 0;
                    BOOL done = NO;
                    do {
    
                        UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil);
                        currentPage++;
                        [self drawPageNumber:currentPage];
                        currentRange = [self renderPage:currentPage withTextRange:currentRange andFramesetter:framesetter];
                        if (currentRange.location == CFAttributedStringGetLength((CFAttributedStringRef)currentText))
    
                            done = YES;
    
                    } while (!done);
                    UIGraphicsEndPDFContext();
                   CFRelease(framesetter);
                } else {
    
                    NSLog(@"Could not create the framesetter needed to lay out the atrributed string.");
    
                }
    
                // Release the attributed string.
    
                CFRelease(currentText);
    
            } else {
    
                NSLog(@"Could not create the attributed string for the framesetter");
    
            }
        }
        // Use Core Text to draw the text in a frame on the page.
    
        - (CFRange)renderPage:(NSInteger)pageNum withTextRange:(CFRange)currentRange
    
               andFramesetter:(CTFramesetterRef)framesetter
    
        {
    
            // Get the graphics context.
    
            CGContextRef    currentContext = UIGraphicsGetCurrentContext();
            CGContextSetTextMatrix(currentContext, CGAffineTransformIdentity);
            CGRect    frameRect = CGRectMake(72, 72, 468, 648);
            CGMutablePathRef framePath = CGPathCreateMutable();
            CGPathAddRect(framePath, NULL, frameRect);
            CTFrameRef frameRef = CTFramesetterCreateFrame(framesetter, currentRange, framePath, NULL);
            CGPathRelease(framePath);
            CGContextTranslateCTM(currentContext, 0, 792);
            CGContextScaleCTM(currentContext, 1.0, -1.0);
            CTFrameDraw(frameRef, currentContext);
            currentRange = CTFrameGetVisibleStringRange(frameRef);
            currentRange.location += currentRange.length;
            currentRange.length = 0;
            CFRelease(frameRef);
            return currentRange;
    
        }
        - (void)drawPageNumber:(NSInteger)pageNum
    
        {
    
            NSString *pageString = [NSString stringWithFormat:@"Page %d", pageNum];
            UIFont *theFont = [UIFont systemFontOfSize:12];
            CGSize maxSize = CGSizeMake(612, 72);
            CGSize pageStringSize = [pageString sizeWithFont:theFont constrainedToSize:maxSize lineBreakMode:UILineBreakModeClip];
            CGRect stringRect = CGRectMake(((612.0 - pageStringSize.width) / 2.0),720.0 + ((72.0 - pageStringSize.height) / 2.0),pageStringSize.width,pageStringSize.height);
               [pageString drawInRect:stringRect withFont:theFont];
    
        }
    

    【讨论】:

    • 感谢回复。这会根据 textView 中字符串的长度生成多页 PDF 文件吗?
    【解决方案3】:
    //StartNewPage
                    UIGraphicsBeginPDFPageWithInfo(pageFrame, nil);
    

    如果输入的文本视图中文本的高度超过您的页框设置,请调用此方法 PageFrame是pdf的新页框

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-13
      • 1970-01-01
      • 2022-11-10
      • 2015-12-07
      • 2010-09-05
      • 2021-11-30
      • 2012-01-23
      • 1970-01-01
      相关资源
      最近更新 更多